Java Design Pattern “Design Patterns are recurring solution to design problems” Presentation By: Himanshu Kumar Upadhyay
Definitions • “Pattern” as the name suggests, means series of events occurring in a definite order. • Design patterns are just convenient ways of reusing object-oriented code between projects and between programmers. The idea behind design patterns is simple-- write down and catalog common interactions between objects that
Pattern Categories There are 23 design patterns in Java. These patterns are grouped under three heads: 1. Creational Patterns 2. Structural Patterns 3. Behavioral Patterns
Creational Pattern All the creational patterns define the best possible way in which an object can be instantiated. These describes the best way to CREATE object instances. Now everyone knows the object instance in Java can be created using a new operator.
Type Of Creational Patterns There are five type of creational patterns Factory Pattern Abstract Factory Pattern Builder Pattern Prototype Pattern Singleton Pattern
Factory Pattern The Problem:
One of the goals of object-oriented design is to delegate responsibility among different objects. This kind of partitioning is good since it encourages Encapsulation and Delegation. • Sometimes, an Application (or framework) at runtime, cannot anticipate the class of object that it must create. The Application (or framework) may know that it has to instantiate classes, but it may only know about abstract classes (or interfaces), which it cannot instantiate. Thus the Application class may only know when it has to instantiate a new Object of a class, not what kind of subclass to create. • a class may want it's subclasses to specify the objects to be created. • a class may delegate responsibility to one of several helper subclasses so that knowledge can be localized
Factory Pattern
(cont…)
Difinition:
The essence of the Factory Pattern is to "Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.“ If we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern
.
Factory methods are common in toolkits and frameworks where library code needs to create objects of types which may be subclassed by applications using the framework. The BorderFactory class in java used combination of Factory and Singleton pattern
Abstract Factory Pattern A software design pattern, the Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme. In normal usage, the client software would create a concrete implementation of the abstract factory and then use the generic interfaces to create the concrete objects that are part of the theme. The client does not know (or care) about which concrete objects it gets from each of these internal factories since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from its general usage. The Abstract Factory pattern is one level of abstraction higher than the factory pattern. You can use this pattern when you want to return one of several related classes of
Abstract Factory Pattern (cont…) • In Java the pluggable look-and-feel classes accomplish this at the system level so that instances of the visual interface components are returned correctly once the type of lookand-feel is selected by the program. Here we find the name of the current windowing system and then tell the PLAF abstract factory to generate the correct objects for us. String laf = UIManager.getSystemLookAndFeelClassName(); try { UIManager.setLookAndFeel(laf); } catch (UnsupportedLookAndFeelException exc){ System.err.println("UnsupportedL&F: " + laf); } catch (Exception exc){ System.err.println("Error loading " + laf); }
Builder Pattern “The Builder Pattern separates the construction of a
complex object from its representation so that the same construction process can create different representations”. The Builder Pattern consists of a Builder, ConcreteBuilder, Director and Product. The Director object is responsible for the construction process of the complex object but delegates the actual creation and assembly to the Builder interface. The Builder object specifies the interface for creating parts of the complex object. The Product represents the complex object that is created by the ConcreteBuilder objects. The Product consists of multiple parts that are created separately by the ConcreteBuilder objects. The ConcreteBuilder objects create and assemble the parts that make up the Product through the Builder interface.
Builder Pattern
(cont….)
Prototype Pattern A prototype pattern is a used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. To implement the pattern, declare an abstract base class that specifies a pure virtual clone() method. Any class that needs a "polymorphic constructor" capability derives itself from the abstract base class, and implements the clone() operation. Cloning In Java:
Prototype Pattern
(cont…)
Singleton Pattern “Ensure a class only has one instance, and provide a global point of access to it.” The Singleton Pattern can be implemented in Java in one of several ways. Creating Singleton Pattern by Using Static Variable Static Class Using Static Method
Singleton Pattern
(cont…)
By Static Variable: In this approach, we create a static
variable which is used to maintain the single instance of class. class PrintSpooler { static boolean instance_flag = false; //true if 1 instance public PrintSpooler() throws Singleton Exception { if (instance_flag) throw new SingletonException("Only one spooler allowed"); else instance_flag = true; //set flag for 1 instance System.out.println("spooler opened"); } public void finalize() { instance_flag = false; //clear if destroyed }
Singleton Pattern
(cont…)
By Static Class: In this approach, all methods and fields of the class is declared static. There already is a kind of Singleton class in the standard Java class libraries: the Math class. This is a class that is declared final and all methods are declared static. One advantage of the final class approach is that you don’t have to wrap things in awkward try blocks. The disadvantage is that if you would like to drop the restrictions of Singleton status, this is easier to do in the exception style class structure. We’d have a lot of reprogramming to do to make the static approach allow multiple instances.
Singleton Pattern By Static Method:
(cont…)
In this approach, we make the constructor private so an instance can be created from within static method of the class. It’s overcome both of the problems which is mentioned in previous approaches. class PrintSpooler { static PrintSpooler printSpooler; private PrintSpooler() { // ---------} public PrintSpooler getSpoolerInstance() { if(printSpooler == null) { printSpooler = new PrintSpooler(); }
Structural Pattern Structural patterns describe how classes and objects can be combined to form larger structures. The difference between class patterns and object patterns is that class patterns describe how inheritance can be used to provide more useful program interfaces. Object patterns, on the other hand, describe how objects can be composed into larger structures using object composition, or the inclusion of objects within other objects.
Type of Structural Patterns There are seven type of Structural patterns Adapter Pattern Bridge Pattern Composite Pattern Decorator Pattern Facade Pattern Flyweight Pattern Proxy Pattern
Adapter Pattern “This pattern establishes a relationship between the two unrelated interfaces such that they work together. This is similar to the conversion of one interface of one class to the interface expected by the client.” An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface. The adapter translates calls to its interface into calls to the original interface, and the amount of code necessary to do this is typically small. The adapter is also responsible for transforming data into appropriate forms. For instance, if multiple boolean values are stored as a single integer but your consumer requires a 'true'/'false',
Bridge Pattern The bridge pattern is a design pattern used in software engineering which is meant to "decouple an abstraction from its implementation so that the two can vary independently“. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes. When a class varies often, the features of objectoriented programming become very useful because changes to a program's code can be made easily with minimal prior knowledge about the program. The bridge pattern is useful when both the class as well as what it does varies. The class itself can be thought of as the implementation and what the class can do as the abstraction. The bridge pattern can also be thought of as
Composite Pattern Composite allows a group of objects to be treated in the same way as a single instance of an object. The intent of composite is to "compose" objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions uniformly. Composite can be used when clients should ignore the difference between compositions of objects and individual objects. If programmers find that they are using multiple objects in the same way, and often have nearly identical code to handle each of them, then composite is a good choice; it is less complex in this situation to treat primitives and composites as homogeneous.
Decorator Pattern “The decorator pattern is a design pattern that allows new/additional behaviour to be added to an existing class dynamically”
.
The Decorator pattern provides us with a way to modify the behavior of individual objects without having to create a new derived class. Suppose we have a program that uses eight objects, but three of them need an additional feature. You could create a derived class for each of these objects, and in many cases this would be a perfectly acceptable solution. However, if each of these three objects require different modifications, this would mean creating three derived classes. Further, if one of the classes has features of both of the other classes, you begin to create a complexity that is both confusing and unnecessary.
Facade Pattern A facade is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can: – make a software library easier to use and understand, since the facade has convenient methods for common tasks; – make code that uses the library more readable, for the same reason; – reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system – wrap a poorly-designed collection of APIs with a single welldesigned API.
An Adapter is used when the wrapper must respect a particular interface and must support a polymorphic behavior. On the other hand a facade is used when one
Facade Pattern
Flyweight Pattern • There are cases in programming where it seems that you need to generate a very large number of small class instances to represent data. Sometimes you can greatly reduce the number of different classes that you need to instantiate if you can recognize that the instances are fundamentally the same except for a few parameters. If you can move those variables outside the class instance and pass them in as part of a method call, the number of separate instances can be greatly reduced.
Proxy Pattern