Design pattern is a general reusable solution to a commonly occurring problem where we use best practices in the programming world. Well there are two sides to everything, so there exists Anti – patterns. Anti pattern is a common response to a recurring problem that is usually ineffective and risks being highly counterproductive. few examples are God object, Constant interface, Call super and etc.
Talking about design patterns, The Gang of Four (Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides) patterns are generally considered the foundation for all other patterns. They are categorized in three groups as Creational Patterns, Structural Patterns and Behavioral Patterns, where there exist 23 design patterns. Plus there is J2EE patterns group which was introduced formerly by Sun Java now Oracle.
These patterns provide ways to assign responsibilities to classes to instantiate new objects while hiding the creation logic. Singleton, Multiton, Object pool, Prototype, Factory, Factory Method, Abstract factory and Builder all fall under Creational Patterns.
Lets talk about singleton. This patter is used when an application needs only one instance of an object, a class of which a single instance can exist.
Here is an example,
One specialty of this pattern is we make the constructor private or protected. By doing this we can ensure that no more than one object can be created at a time, you prevent class instances from being created in any place other than this very class.
What if a multi threaded environment is accessing this, well we can improve it using synchronization as follows.
Finally, you cannot create instance of the class like you usually do.
Multition pattern is very similar to singleton. When a request is made for an object, a key is passed to the static method If the key has not been used before, a new object is instantiated, linked to the key and returned, If the key has been used before, the object previously linked to that key is returned, Thus multiton provides the functionality of a group of singletons.
These patterns ease the design by identifying a simple way to realize relationships between entities. Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Private Class Data and Proxy are few examples.
Behavioral design patterns are design patterns that identify and realize common communication patterns between objects where objective is to increase flexibility in carrying out this communication. Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, Visitor, Strategy, Template Method and State all fall under Behavioral pattern group.
To find more about implementation methods (Java) visit : Github Repository