{"id":21240669,"url":"https://github.com/sdmg15/java-design-patterns","last_synced_at":"2026-03-12T05:31:07.994Z","repository":{"id":65980420,"uuid":"85346790","full_name":"sdmg15/Java-design-patterns","owner":"sdmg15","description":" Java Design patterns. ","archived":false,"fork":false,"pushed_at":"2018-09-07T08:45:08.000Z","size":23,"stargazers_count":54,"open_issues_count":0,"forks_count":44,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-10-09T05:23:45.085Z","etag":null,"topics":["builder-pattern","design-patterns","factory-pattern","inheritance","java","prototype-pattern","singleton-pattern"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sdmg15.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-03-17T19:15:03.000Z","updated_at":"2025-03-13T13:56:01.000Z","dependencies_parsed_at":"2023-02-19T18:45:17.234Z","dependency_job_id":null,"html_url":"https://github.com/sdmg15/Java-design-patterns","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/sdmg15/Java-design-patterns","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sdmg15%2FJava-design-patterns","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sdmg15%2FJava-design-patterns/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sdmg15%2FJava-design-patterns/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sdmg15%2FJava-design-patterns/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sdmg15","download_url":"https://codeload.github.com/sdmg15/Java-design-patterns/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sdmg15%2FJava-design-patterns/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30416310,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-12T04:41:02.746Z","status":"ssl_error","status_checked_at":"2026-03-12T04:40:12.571Z","response_time":114,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["builder-pattern","design-patterns","factory-pattern","inheritance","java","prototype-pattern","singleton-pattern"],"created_at":"2024-11-21T00:52:30.494Z","updated_at":"2026-03-12T05:31:07.977Z","avatar_url":"https://github.com/sdmg15.png","language":"Java","readme":"# Java Design Patterns\n\nDesign Patterns are very popular among software developers. A design pattern is a well-described solution to\ncommon software problem.\n\nSome of benefits of using design patterns are :\n  * Design patterns are already defined and provides industry standard approach to solve recurring problem,\n    so it saves time if we  use  the design pattern .\n  * Using design pattern promotes re-usability that leads to more robust and highly maintainable code.\n  * Since design patterns are already defined, it makes out code easy to understand and debug. It lead to faster development and new members of team understand it easily.\n\n\n__What is a Design Pattern ?__\n   \u003e A software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design --- Wikipedia\n\n__Java Design Patterns__ are divided into tree parts : __Creational__, __Structural__ and __Behavioral__.\n\n## CREATIONAL DESIGN PATTERNS\n\n  Creational design pattens provide solution to instantiate an object in the best possible way for specific situations.\n  The basic form of object creation could result in design problems or add unwanted complexity to the design. Creational design patterns solve this problem by __controlling the object creation__ by different ways.\n  There are five creational design patterns that we will discuss on :\n\n* Singleton Pattern\n* Factory Pattern\n* Abstract Factory Pattern\n* Builder Pattern\n* Prototype Pattern\n\n### Pattern Singleton\n\n Pattern Singleton: \u003e One Class, one Instance.\n\n  Singleton is one of the Gangs of Four Design patterns and comes in the Creational Design Pattern category.\nSingleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the Java virtual machine. The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, driver objects, caching and thread pool. Singleton design pattern is also used in other design patterns like __Abstract Factory__, __Builder__, __Prototype__, __Facade__ etc. Singleton design pattern is used in core Java classes also, for example __java.lang.Runtime__ , __java.awt.Desktop__.\n\nTo implement Singleton pattern, there are really many approaches but all of them have following common concepts:\n\n* A private constructor to avoid instantiation of the class,\n* A private static variable from the same class that's the only instance of the class.\n* public static method that returns the instance of the class, this is the global access point for the outer world to\n  get the instance of the class.\n\nWe'll implement the thread safe one here. Classes are in the package `com.singleton`;\n\n ```java    \n import  com.singleton.SingletonThreadSafe;\n\n   public class SingletonTest {\n      public static void main(String[] args){\n        SingletonThreadSafe sing = SingletonThreadSafe.getInstance();\n        System.out.println(sing);\n\n        // Now let's instanciate another class\n\n        SingletonThreadSafe sing1 = SingletonThreadSafe.getInstance();\n\n        System.out.println(sing1);\n\n        //Now check out your console.... What the hell, the two instances have the same reference :o\n        }\n      }\n  ```\n### Pattern Factory\n\nFactory design pattern is used when we have a super class with multiple sub-classes and based on input, we need to return one of the sub-class. This pattern take out the responsibility of instantiation of a class from client program   to   the   factory   class.   Let’s   first   learn   how   to   implement   factory  pattern in Java and then we will learn its benefits and we will see its usage in JDK.\n\n* Super Class : Super class in factory pattern can be an interface, abstract class or a normal Java class. For our example, we have super class as abstract class with overridden toString() method for testing purpose.\n  see `com.factory`.\n* sub-classes: Let’s  say  we  have  two  sub-classes PC and Server with implementation in `com.factory`\n\nHere's what we have in image :\n  [](http://zupimages.net/up/17/13/7w9z.png)\n\nNow let's write the test class.\n\n  ```java\n    import com.factory.FactoryClass ; //The factory class\n    import com.factory.PC; //sub-class\n    import com.factory.Server; //sub-class\n    //PC and Server classes extend from Computer.\n\n    public static void main(String[] args){\n\n      FactoryClass fc = new FactoryClass();\n      Computer comp1 = fc.getComputer(\"PC\",16,499,4.3);\n      System.out.println(comp1);\n\n\n      Computer comp2 = fc.getComputer(\"Server\",30,900,9);\n      System.out.println(comp2);\n\n    //Now you can see the output in your console.\n    }\n ```\nThis pattern provides some advantages such as :\n\n  * It provides approach to code for the interface rather than the implementation.\n  * It removes the instantiation of the actual implementation classes from client code, making it more robust.\n  * It provides abstraction between implementation and client classes through inheritance.\n\n  As examples of its  implementation in JDK we have :\n\n  * *java.util.Calendar*, *ResourceBundle()* and *NumberFormat getInstance()*;\n  * *valueOf()* method in wrapper classes like Boolean , Integer etc.\n\n### Abstract Factory\n\nThis is one of the Creational Pattern and almost similar to Factory Pattern except the fact that it's most like\nFactory of factories. If you're familiar with __factory design pattern in java__ , you'll notice that we have a single Factory class that returns the different sub-classes based on the input provided and the factory class uses if-else or switch statement to achieve this. Like our factory pattern post, we will use the same super class and sub-classes.\n  Codes are available in `com.abstractFactory`.\nHere's the implementation of the test class:\n\n```java\n\n    public class abstractFactoryTest{\n      public static void main(String[] args){\n\n        Computer c = ComputerFactory.getComputer(new PCFactory(\"4G\",\"400G\",\"2.9Ghz\"));\n        /* ComputerFactory class contains static method getComputer(abstractFactory fac) */\n       System.out.print(c);\n\n      }\n    }\n```\n\n### Pattern Builder\n\nBuilder pattern is a creational design pattern as Factory Pattern and Abstract Factory Pattern. This pattern was introduced to solve some of the problems with Factory and Abstract Factory patterns when the Object contains a lot of attributes. This pattern deals with a static nested class and then copy all the arguments from the outer class to the Builder class.\nThe sample code where we have a Computer class and ComputerBuilder to build it are available in the package `com.builder.Computer`.\nHere's a test program showing how to use Builder class to get object.\n\n\n```java\n\n  import com.builder.Computer;\n\npublic class TestBuilderPattenr{\n  public static void main(String[] args){\n\n      Computer comp = new Computer.ComputerBuilder(\n      \"500 GB\",\"2 GB\").setBluetoothEnabled(true)\n      .setGraphicsCardEnabled(true).build(); // -)\n      )\n  }\n\n}\n```\nThere are really various implementations of this pattern in JDK : java.lang.StringBuilder#append() (unsynchronized) java.lang.StringBuffer#append() (synchronized) .\n\n### Pattern Prototype\n\nPrototype pattern is one of the Creational Design pattern, so it provides a mechanism of object creation. Prototype pattern is used when the Object creation is a costly affair and requires a lot of time and resources and you have a similar object already existing. So this pattern provides a mechanism to copy the original object to a new object and then modify it according to our needs. This pattern uses Java cloning to copy the object.\n\n```java\n\nimport java.util.ArrayList;\nimport java.util.List;\npublic class Users implements Cloneable{\n    private List\u003cString\u003e empList;\n\n    public Users(){\n\n      empList = new ArrayList\u003c\u003e();\n      }\n\npublic Users(List\u003cString\u003e list){\nthis.empList=list;\n}\n\n//read some data from the database.\npublic void loadData(){\n    empList.add(\"japak\");\n    empList.add(\"King\");\n    empList.add(\"David\");\n    empList.add(\"Romeo\");\n}\n\npublic List\u003cString\u003e getEmpList() {\n    return empList;\n}\n\n  @Override\n  public Object clone() throws CloneNotSupportedException{\n        List\u003cString\u003e temp = new ArrayList\u003cString\u003e();\n        for(String s : this.getEmpList()){\n          temp.add(s);\n          }\n          return new Users(temp);\n}\n}\n\n //Notice that the clone method is overridden to provide a deep copy of the users list.\n```\n\nHere's the program that will show the benefit of the Prototype pattern usage.\n\n```java\npublic class PrototypePatternTest {\n  public static void main(String[] args) throws CloneNotSupportedException {\n        Users usr = new Users();\n          user.loadData();\n//Use the clone method to get the User object\n        Users useNew = (Users) user.clone();\n        Users useNew1 = (Users) user.clone();\n        List\u003cString\u003e list = useNew.getEmpList();\n        list.add(\"John\");\n\n        List\u003cString\u003e list1 = usersNew1.getEmpList();\n        list1.remove(\"Pankaj\");\n        System.out.println(\"users List: \"+ users.getEmpList());\n        System.out.println(\"users New List: \"+list);\n        System.out.println(\"users New1 List: \"+list1);\n      }\n}\n```\n\n## STRUCTURAL DESIGN PATTERNS\n\n Structural Patterns provide different ways to create a class structure, for example using inheritance and composition\n to create a large object from small objects.\n\n### Adapter  Pattern\n\nThis pattern is used in such a way that two unrelated interfaces can work together. The object that joins these   unrelated interfaces is called Adapter. As a real life example, we can think of a mobile charger as an adapter because mobile battery needs 3 Volts to charge but the normal socket produces either 120V (US) or 240V (India). So the mobile charger works as an adapter between mobile charging socket and the wall socket.\nFirst of all we'll have two classes : Volt - to measure volts) and Socket :\n\n```java\n\npublic class Volt {\n  private int volts;\n      public Volt(int v){\n        this.volts=v;\n        }\n        public int getVolts() {\n          return volts;\n        }\n   public void setVolts(int volts) {\n     this.volts = volts;\n    }\n}\n\n\npublic class Socket {\n  public Volt getVolt(){\n  return new Volt(120);\n}\n\n}\n```\nNow we want to build an adapter that can produce 3 volts, 12 volts and default 120 volts. So first of all we will  create an adapter interface with these methods.\n\n```java\npublic interface SocketAdapter {\npublic Volt get120Volt();\npublic Volt get12Volt();\npublic Volt get3Volt();\n}\n\n```\n\nwhile implementing this pattern, there are two approaches : one that deals with inheritance and another one that deals with Composition. Note that they are almost the same thus, here we'll deal with one with inheritance. Let's implement out adapter  class !\n\n\n```java\npublic class SocketClassAdapterImpl extends Socket implements\n    SocketAdapter{\n    @Override\n    public Volt get120Volt() {\n      return getVolt();\n    }\n    @Override\n    public Volt get12Volt() {\n      Volt v= getVolt();\n      return convertVolt(v,10);\n    }\n    @Override\n    public Volt get3Volt() {\n      Volt v= getVolt();\n      return convertVolt(v,40);\n    }\n    private Volt convertVolt(Volt v, int i) {\n        return new Volt(v.getVolts()/i);\n    }\n}\n```\nNow let's see how all this work ! Here's a test Main function to illustrate.\n\n\n```java\n\npublic class AdapterPatternTest {\n\n  public static void main(String[] args) {\n      testClassAdapter();\n\n      testAdapter();\n\n      //The results goes in your console :)\n}\n\nprivate static void testAdapter() {\n  SocketAdapter sockAdapter = new SocketObjectAdapterImpl();\n\n  Volt v3 = getVolt(sockAdapter,3);\n\n  Volt v12 = getVolt(sockAdapter,12);\n\n  Volt v120 = getVolt(sockAdapter,120);\n\n  System.out.println(\"v3 volts using Object Adapter=\"+v3.getVolts());\n  System.out.println(\"v12 volts using Object Adapter=\"+v12.getVolts());\n  System.out.println(\"v120 volts using Object Adapter=\"+v120.getVolts());\n}\n\nprivate static Volt getVolt(SocketAdapter sockAdapter, int i) {\n  switch (i){\n    case 3: return sockAdapter.get3Volt();\n    case 12: return sockAdapter.get12Volt();\n    case 120: return sockAdapter.get120Volt();\n    default: return sockAdapter.get120Volt();\n    }\n}\n}\n```\nThis pattern has many usage in the JDK :\n * __java.util.Arrays#asList() java.io.InputStreamReader(InputStream)__ (returns a Reader),\n * __java.io.OutputStreamWriter(OutputStream)__ (returns a Writer).\n\n### Composite Pattern   \n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsdmg15%2Fjava-design-patterns","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsdmg15%2Fjava-design-patterns","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsdmg15%2Fjava-design-patterns/lists"}