Ce diaporama a bien été signalé.
Le téléchargement de votre SlideShare est en cours. ×

Creational Design Patterns.pptx

Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Publicité
Prochain SlideShare
Gof design patterns
Gof design patterns
Chargement dans…3
×

Consultez-les par la suite

1 sur 25 Publicité

Creational Design Patterns.pptx

Télécharger pour lire hors ligne

What are design Patterns
Definition
Characteristics
Benefits
Categorizing
What are Creational Design Patterns
Singleton Pattern
Prototype Pattern
Build Pattern
Factory Pattern
Abstract Factory Pattern

What are design Patterns
Definition
Characteristics
Benefits
Categorizing
What are Creational Design Patterns
Singleton Pattern
Prototype Pattern
Build Pattern
Factory Pattern
Abstract Factory Pattern

Publicité
Publicité

Plus De Contenu Connexe

Similaire à Creational Design Patterns.pptx (20)

Publicité

Creational Design Patterns.pptx

  1. 1. Design Patterns- Creational - Sachin Kumar Patidar
  2. 2. Content 1 What are design Patterns • Definition • Characteristics • Benefits • Categorizing 2 What are Creational Design Patterns • Singleton Pattern • Prototype Pattern • Build Pattern • Factory Pattern • Abstract Factory Pattern
  3. 3. What are Design Patterns Dictionary meaning of Pattern: “A plan, diagram, or model to be followed in making things” A software designer or an architect needs to understand more than the relevant APIs, which includes • What are the best practices? • What are the bad practices? • What are the common recurring problems and proven solutions to these problems? • How is code re-factored from a less optimal scenario, or bad practice, to a better one typically described by a pattern?
  4. 4. What are Design Patterns Some Definitions of Design Pattern A design pattern is like a template that can be applied in many different situations. Patterns are neither code, nor designs as they must be instantiated and applied. •evaluate trade-offs and impact of using a pattern in the system at hand •make design and implementation decision how best to apply the pattern, perhaps modify it slightly •implement the pattern in code and combine it with other patterns “A design pattern is a general repeatable solution to a commonly occurring problem in software design. It is a description or template for how to solve a problem that can be used in many different situations.”
  5. 5. What are Design Patterns There are many definitions for a pattern, but all these definitions have a common theme. Some of the common characteristics of patterns are: • Patterns are observed through experience. • Patterns are typically written in a structured format called Template. • Patterns prevent reinventing the wheel. • Patterns exist at different levels of abstraction. • Patterns undergo continuous improvement. • Patterns are reusable artifacts. • Patterns can be used together to solve a larger problem.
  6. 6. Design Patterns - Benefit Benefits of Using Patterns: •Patterns are a common design vocabulary • they allow engineers to abstract a problem and talk about that abstraction in isolation from its implementation. •Patterns capture design expertise and allow that expertise to be communicated •Promote design reuse and avoid mistakes •Improve documentation (less is needed) and understandability (patterns are described well once)
  7. 7. Design Patterns - Categorizing Patterns have been captured at many levels of abstraction and in numerous domains. Numerous categories have been suggested for classifying software patterns, with some of the most common being •creational patterns abstract the object instantiation process •structural patterns describe how classes and objects can be combined to form larger Structures •behavioral patterns concerned with communication, algorithms and the assignment of responsibilities between objects
  8. 8. Creational Patterns This Design pattern is all about class instantiation. Defines the best possible way in which an object can be instantiated • Make system independent of how objects are created composed and represented • Class-creation: • use inheritance effectively in the instantiation process • Object-creation: • use delegation effectively to get the job done
  9. 9. Creational Patterns • Factory Method Pattern Define an interface for creating an object, but let subclasses decide which class to instantiate. • Abstract Factory Pattern Provide an interface for creating families of related or dependent objects without specifying their concrete classes. • Builder Pattern Separate the construction of a complex object from its representation so that the same construction process can create different representations • Prototype Pattern Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. • Singleton Pattern Ensure a class has only one instance and provide a global point of access to it.
  10. 10. Singleton Motivation: Sometimes it's important to have only one instance for a class. For example, in a system there should be only one window manager (or only a file system or only a print spooler). Intent • Ensure that only one instance of a class is created. • Provide a global point of access to the object Implementation The implementation involves a static member in the "Singleton" class, a private constructor and a static public method that returns a reference to the static member.
  11. 11. Singleton Typically the class code looks like class Singleton { private static Singleton instance; private static lockObject = new Object() private Singleton() { ... } public static Singleton getInstance() { if (instance == null) { lock(lockObject) { if (instance == null) instance = new Singleton(); } } return instance; } public void doSomething() { ... } } Applicability & Examples • Logger Classes • Configuration Classes • Accessing resources in shared mode • Factories implemented as Singletons
  12. 12. Prototype Motivation: • If the cost of creating a new object is large and creation is resource intensive, we clone the object. • We clone the existing object and change the state of the object as needed. Intent: • specifying the kind of objects to create using a prototypical instance • creating new objects by copying this prototype object to avoid creation Implementation The pattern uses abstract classes, and only three types of classes make its implementation rather easy. • Client - creates a new object by asking a prototype to clone itself. • Prototype - declares an interface for cloning itself. • ConcretePrototype - implements the operation for cloning itself.
  13. 13. Prototype Typically the class code looks like public interface Prototype { public abstract public interface Prototype Clone( ); } public class ConcretePrototype : Prototype { public override Prototype Clone() { //Shallow copy return (Prototype)this.MemberwiseClone(); } } public class Client { public static void main( String arg[] ) { ConcretePrototype obj1= new ConcretePrototype (); ConcretePrototype obj2 = (ConcretePrototype)obj1.Clone(); } }
  14. 14. Prototype Applicability Use Prototype Pattern when a system should be independent of how its products are created, composed, and represented. • Classes to be instantiated are specified at run-time for example, by dynamic loading • It is more convenient to copy an existing instance than to create a new one. • When instances of a class can have one of only a few different combinations of state. Examples • Analysis on a set of data from the database.
  15. 15. Factory Motivation: Helps to model an interface for creating an object , which at creation time can let its subclasses decide which class to instantiate. Intent: • creates objects without exposing the instantiation logic to the client. • refers to the newly created object through a common interface. • In programmer’s language (very raw form), you can use factory pattern where you have to create an object of any one of sub-classes depending on the data provided. Advantages: • The use of factories gives the programmer the opportunity to abstract the specific attributes of an Object into specific subclasses which create them. • The Factory Pattern promotes loose coupling by eliminating the need to bind application-specific classes into the code.
  16. 16. Factory Implementation • The client needs a product, but instead of creating it directly using the new operator, it asks the factory object for a new product, providing the information about the type of object it needs. • The factory instantiates a new concrete product and then returns to the client the newly created product(casted to abstract product class). • The client uses the products as abstract products without being aware about their concrete implementation. Simplest Implementation public Product createProduct(String ProductID){ if (id==ID1) return new OneProduct(); if (id==ID2) return return new AnotherProduct(); ... // so on for the other Ids return null; //if the id doesn't have any of the expected values }
  17. 17. Abstract Factory Motivation: • This pattern is one level of abstraction higher than factory pattern. • Abstract Factory is a super-factory which creates other factories • Provide an interface for creating families of related or dependent objects. • Factory method takes care of one product where as the abstract factory Pattern provides a way to encapsulate a family of products. Intent: • Provide an interface for creating families of related or dependent objects without explicitly specifying their classes. Applicability: • A system should be independent of how its products are created, composed, and represented. • If you want to provide a class library products, and you want to reveal just their interfaces , not their implementations.
  18. 18. Abstract Factory Implementation Typically the class diagram looks like
  19. 19. Abstract Factory Example: We have a requirement where we need to create control library and the same library supports multiple platforms but the client code should not be changed if we import from one operating system to the other. The solution is
  20. 20. Builder Motivation: Builder, as the name suggests builds complex objects from simple ones step-by- step. It separates the construction of complex objects from their representation. Intent: • Defines an instance for creating an object but letting subclasses decide which class to instantiate using any of the patterns. • Refers to the newly created object through a common interface Advantages: • Encapsulation: The builder pattern encapsulates the construction process of a complex object and thereby increases the modularity of an application.
  21. 21. Builder Implementation The Builder design pattern uses the Factory Builder pattern to decide which concrete class to initiate in order to build the desired type of object. • The Builder class specifies an abstract interface for creating parts of a Product object. • The ConcreteBuilder constructs and puts together parts of the product by implementing the Builder interface. It defines and keeps track of the representation it creates and provides an interface for saving the product. • The Director class constructs the complex object using the Builder interface. • The Product represents the complex object that is being built..
  22. 22. Builder Applicability: • Builder patterns is useful in a large system • Builder patterns fits when different variations of an object may need to be created and the inheritance into those objects is well-defined. • the creation algorithm of a complex object is independent from the parts that actually compose the object Example: • User specific UI: the admin needs to have some buttons enabled, buttons that needs to be disabled for the common user. The Builder provides the interface for building form depending on the login information. The ConcreteBuilders are the specific forms for each type of user. The Product is the final form that the application will use in the given case The Director is the application that, based on the login information, needs a specific form.
  23. 23. Builder
  24. 24. Comparison
  25. 25. Questions and answers Thank You

Notes de l'éditeur

  • Highlight the underlined texts.
  • Leverage a Proven Solution
    A pattern is documented based on the fact that the solution it offers has been used over and over again to solve similar problems at different times in different projects. Thus, patterns provide a powerful mechanism for reuse, helping developers and architects to avoid reinventing the wheel.

    Common Vocabulary
    Patterns provide software designers with a common vocabulary. As designers, we use patterns not only to help us leverage and duplicate successful designs, but also to help us convey a common vocabulary and format to developers.

    Constrains Solution Space
    Pattern application introduces a major design component constraints. Using a pattern constrains or creates boundaries within a solution space to which a design and implementation can be applied. Thus, a pattern strongly suggests to a developer boundaries to which an implementation might adhere. Going outside of these boundaries breaks the adherence to the pattern and design, and may lead to the unwanted introduction of an anti-pattern.
  • What is GoF ?
    Patterns in software were popularized by the book Design Patterns:Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (also known as the Gang of Four, or GoF).

    While the Gang of Four work resulted in patterns becoming a common discussion topic in software development teams around the world, the important point to remember is that the patterns they describe were not invented by these authors.

    Instead, having recognized recurring designs in numerous projects, the authors identified and documented this collection.

    Many software patterns books have been published since the GoF book, covering patterns for various domains and purposes.
  • Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.


    The pattern explains how you can achieve the singleton class. It says to have the constructor as private and have a static method to access the instance of the class using that method.
  • You can notice in the above code that getInstance method ensures that only one instance of the class is created.

    The constructor should not be accessible from the outside of the class to ensure the only way of instantiating the class would be only through the getInstance method.


    Example 1 - Logger Classes
    provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.

    Example 2 - Configuration Classes
    Used in classes which provides the configuration settings for an application. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure.

    If the values are read from the database or from files this avoids the reloading the values each time the configuration parameters are used.
     
    Example 3 - Accesing resources in shared mode
    It can be used in the design of an application that needs to work with the serial port. Let's say that there are many classes in the application, working in an multi-threading environment, which needs to operate actions on the serial port. In this case a singleton with synchronized methods could be used to be used to manage all the operations on the serial port.

    Example 4 - Factories implemented as Singletons
    Let's assume that we design an application with a factory to generate new objects(Acount, Customer, Site, Address objects) with their ids, in an multithreading environment. If the factory is instantiated twice in 2 different threads then is possible to have 2 overlapping ids for 2 different objects. If we implement the Factory as a singleton we avoid this problem. Combining Abstract Factory or Factory Method and Singleton design patterns is a common practice.
  • The main application of such pattern is when the object creation is costly.

    As an example we have a database class the constructor sets up the database for the class. Now for each new user logging to the system once the system is up we don't setup the database but just clone the first object and change the user specific details like user name / password to validate the user.
  • The process of cloning starts with an initialized and instantiated class. The Client asks for a new object of that type and sends the request to the Prototype class. A of the ConcretePrototype, depending type of object is needed, will handle the cloning through making a new instance of itself.
    the Clone() method,
  • Suppose we are doing a sales analysis on a set of data from a database. Normally, we would copy the information from the database, encapsulate it into an object and do the analysis. But if another analysis is needed on the same set of data, reading the database again and creating a new object is not the best idea. If we are using the Prototype pattern then the object used in the first analysis will be cloned and used for the other analysis.
    The Client is here one of the methods that process an object that encapsulates information from the database. The ConcretePrototype classes will be classes that, from the object created after extracting data from the database, will copy it into objects used for analysis.
  • Do we need to have derived classes figure out what to instantiate and decouple client from instantiated class.

    Factory of what? Of classes. In simple words, 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.
  • Client uses the factory to create products and its the factory which decides when the actual product is needed for instantiation. This way client decouples the instance and can be saved from some of the crucial operations of object copy if the type of object may change after creation.
  • This means that the abstract factory returns the factory of classes. Like Factory pattern returned one of the several sub-classes, this returns such factory which later will return one of the sub-classes.
  • AbstractFactory - declares a interface for operations that create abstract products.
    ConcreteFactory - implements operations to create concrete products.
    AbstractProduct - declares an interface for a type of product objects.
    Product - defines a product to be created by the corresponding ConcreteFactory; it implements the AbstractProduct interface.
    Client - uses the interfaces declared by the AbstractFactory and AbstractProduct classes.


    abstract class AbstractProductA{
    public abstract void operationA1();
    public abstract void operationA2();
    }

    class ProductA1 extends AbstractProductA{
    ProductA1(String arg){
    System.out.println("Hello "+arg);
    } // Implement the code here
    public void operationA1() { };
    public void operationA2() { };
    }

    class ProductA2 extends AbstractProductA{
    ProductA2(String arg){
    System.out.println("Hello "+arg);
    } // Implement the code here
    public void operationA1() { };
    public void operationA2() { };
    }

    abstract class AbstractProductB{
    //public abstract void operationB1();
    //public abstract void operationB2();
    }

    class ProductB1 extends AbstractProductB{
    ProductB1(String arg){
    System.out.println("Hello "+arg);
    } // Implement the code here
    }

    class ProductB2 extends AbstractProductB{
    ProductB2(String arg){
    System.out.println("Hello "+arg);
    } // Implement the code here
    }

    abstract class AbstractFactory{
    abstract AbstractProductA createProductA();
    abstract AbstractProductB createProductB();
    }

    class ConcreteFactory1 extends AbstractFactory{
    AbstractProductA createProductA(){
    return new ProductA1("ProductA1");
    }
    AbstractProductB createProductB(){
    return new ProductB1("ProductB1");
    }
    }

    class ConcreteFactory2 extends AbstractFactory{
    AbstractProductA createProductA(){
    return new ProductA2("ProductA2");
    }
    AbstractProductB createProductB(){
    return new ProductB2("ProductB2");
    }
    }

    //Factory creator - an indirect way of instantiating the factories
    class FactoryMaker{
    private static AbstractFactory pf=null;
    static AbstractFactory getFactory(String choice){
    if(choice.equals("a")){
    pf=new ConcreteFactory1();
    }else if(choice.equals("b")){
    pf=new ConcreteFactory2();
    } return pf;
    }
    }

    // Client
    public class Client{
    public static void main(String args[]){
    AbstractFactory pf=FactoryMaker.getFactory("a");
    AbstractProductA product=pf.createProductA();
    //more function calls on product
    }
    }


  • The client uses the GuiFactory to get the required factory of the supported operating system and calls the same Show Method.
    Now depending on the platform we change the factory but the client implementation remains the same.
    If support for new operating system is to be added we need the new factory and the exact implementation of the buttons and without changing the existing code we can support the new platform.
  • The more complex an application is the complexity of classes and objects used increases. Complex objects are made of parts produced by other objects that need special care when being built. An application might need a mechanism for building complex objects that is independent from the ones that make up the object.
  • The client, that may be either another object or the actual client that calls the main() method of the application, initiates the Builder and Director class. The Builder represents the complex object that needs to be built in terms of simpler objects and types. The constructor in the Director class receives a Builder object as a parameter from the Client and is responsible for calling the appropriate methods of the Builder class. In order to provide the Client with an interface for all concrete Builders, the Builder class should be an abstract one. This way you can add new types of complex objects by only defining the structure and reusing the logic for the actual construction process. The Client is the only one that needs to know about the new types, the Director needing to know which methods of the Builder to call.
  • Who is what? Waiter is Director PizzaBuilder is Builder CheesePizzaBuilder and MixedPizzaBuilder are Concretebuilder Pizza is product When Waiter (Director) is asked to serve it creates the Pizza (Product) using the PizzaBuilder.

    The actual client initiates the Builder and Director class. The Builder represents the complex object that needs to be built in terms of simpler objects and types. The constructor in the Director class receives a Builder object as a parameter from the Client and is responsible for calling the appropriate methods of the Builder class

×