What are Design Patterns ? Tutorials

Design Patterns Overview

Design Patterns is a way to record experience in designing object oriented software.The experience is primarily captured and documented with details such as

  • Pattern Name: A word or two, to describe a design problem, its solutions, and consequences. It establishes a vocabulary for patterns and lets us design at a higher level of abstraction
  • Problem: Describes when to apply the pattern, by describing the exact design problem. Also might list down a list of preconditions to be satisfied before the design pattern can be applied meaningfully
  • Solution: Describes the elements that make up the design, their relationships, responsibilities and collaborations. Provides an abstract description of a design problem and how a general arrangement of elements (class/objects) can solve the problem
  • Consequences: Results and trade-offs of applying the pattern. They are critical for evaluating design alternatives and for understanding the cost and benefits of applying the pattern (most non functional aspects like flexibility, space, time etc)

They help designers to avoid designing systems from first principles. They are solutions that are known to solve certain design problem reliably and in turn making object oriented systems more flexible and reusable.
 


Classification of Design Patterns

Design patterns vary in their granularity and level of abstraction because there are many design patterns, we need a way to organize them.
Apart from referring to them as families of related patterns, the classification also helps us to learn the patterns in the catalog faster, and it can direct efforts to find new patterns as well.
Patterns are primarily classified by two criteria:

  • Purpose – Reflects what a pattern does
    • Creational
    • Structural
    • Behavioral
  • Scope – Specifies whether the pattern primarily applies to classes or objects.
    • Object patterns: These patterns deal with object relationships which can be changed at run time and are more dynamic
    • Class patterns: These patterns deal with class relationship which are static in nature.

Purpose

Creational Structural Behavioral
Class 1.Factory Method 1.Adapter 1.Interpreter
2.Template Method
Object 1.Abstract Factory
2.Builder
3.Prototype
4.Singleton
1.Adapter
2.Bridge
3.Composite
4.Decorator
5.Facade
6.Flyweight
7.Proxy
1.Chain of Responsibility
2.Command
3.Iterator
4.Mediator
5.Memento
6.Observer
7.State
8.Strategy
9.Visitor

 


Creational Design Patterns

Creational design patterns abstract the instantiation process.

  • They help make a system independent of how its objects are created, composed, and represented.
  • A class creational pattern uses inheritance to vary the class that’s instantiated, whereas an object creational pattern will delegate instantiation to another object.

There are two recurring themes in Creational design patterns

  • First, they all encapsulate knowledge about which concrete classes the system uses.
  • Second, they hide how instances of these classes are created and put together.
  • All the system at large knows about the objects is their interfaces as defined by abstract classes. Consequently, the creational patterns give you a lot of flexibility in what gets created, who creates it, how it gets created, and when.
  • They let you configure a system with “product” objects that vary widely in structure and functionality. Configuration can be static (that is, specified at compile-time) or dynamic (at run-time).

Creational patterns become important as systems evolve to depend more on object composition than class inheritance.

  • As that happens, emphasis shifts away from hard-coding a fixed set of behaviors toward defining a smaller set of fundamental behaviors that can be composed into any number of more complex ones.
  • Thus creating objects with particular behaviors requires more than simply instantiating a class.
  • The key to remember is that Creational design patterns allow creational flexibility (i.e. what gets created, when it gets created, how it gets created, who creates it etc).



Factory Method

1. Intent

  • Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

2. Applicability

  • A class can’t anticipate the class of objects it must create.
  • A class wants its subclasses to specify the objects it creates.
  • Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.

3. Participants

  • Product – defines the interface of objects the factory method creates.
  • ConcreteProduct – implements the Product interface.
  • Creator – declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.
  • may call the factory method to create a Product object.
  • ConcreteCreator – overrides the factory method to return an instance of a ConcreteProduct.

4. Structure
 

Design Patterns
Factory Method

5. Consequences

  • Provides hooks for subclasses
    • Creating objects inside a class with a factory method is always more flexible than creating an object directly. Factory Method gives subclasses a hook for providing an extended version of an object.
  • Connects parallel class hierarchies.



Abstract Factory

1. Intent

  • Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

2. Applicability

  • a system should be independent of how its products are created, composed, and represented.
  • a system should be configured with one of multiple families of products.
  • a family of related product objects is designed to be used together, and you need to enforce this constraint.
  • you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.

3. Participants

  • AbstractFactory – declares an interface for operations that create abstract product objects.
  • ConcreteFactory – implements the operations to create concrete product objects.
  • AbstractFactory – declares an interface for operations that create abstract product objects.
  • ConcreteFactory – implements the operations to create concrete product objects.
  • AbstractProduct – declares an interface for a type of product object.
  • ConcreteProduct
    • defines a product object to be created by the corresponding concrete factory.
    • implements the AbstractProduct interface.
  • Client – uses only interfaces declared by AbstractFactory / AbstractProduct classes.

4. Structure
 

Design patterns
Abstract Factory

5. Consequences

  • Isolates concrete classes – Because a factory encapsulates the responsibility and the process of creating product objects, it isolates clients from implementation classes. Clients manipulate instances through their abstract interfaces.
  • Makes exchanging product families easy – The class of a concrete factory appears only once in an application—that is, where it’s instantiated. This makes it easy to change the concrete factory an application uses.
  • Promotes consistency among products – When product objects in a family are designed to work together, it’s important that an application use objects from only one family at a time. AbstractFactory makes this easy to enforce.
  • Supporting new kinds of products is difficult – Extending abstract factories to produce new kinds of Products isn’t easy. That’s because the AbstractFactory interface fixes the set of products that can be created. Supporting new kinds of products requires extending the factory interface, which involves changing the AbstractFactory class and all of its subclasses.



Builder

1. Intent

  • Separate the construction of a complex object from its representation so that the same construction process can create different representations.

2. Applicability

  • the algorithm for creating a complex object should be independent of the parts that make up the object and how they’re assembled.
  • the construction process must allow different representations for the object that’s constructed

3. Participants

  • Builder – specifies an abstract interface for creating parts of a Product object.
  • ConcreteBuilder
    • constructs and assembles parts of the product by implementing the Builder interface.
    • defines and keeps track of the representation it creates.
    • provides an interface for retrieving the product (e.g., GetASCIIText, GetTextWidget).
  • Director – constructs an object using the Builder interface.
  • Product
    • represents the complex object under construction. ConcreteBuilder builds the product’s internal representation and defines the process by which it’s assembled.
    • includes classes that define the constituent parts, including interfaces for assembling the parts into the final result.

4. Structure
 

Builder
Builder

 
5. Consequences

  • It lets you vary a product’s internal representation – The Builder object provides the director with an abstract interface for constructing the product. Because the product is constructed through an abstract interface, all you have to do to change the product’s internal representation is define a new kind of builder.
  • It isolates code for construction and representation – The Builder pattern improves modularity by encapsulating the way a complex object is constructed and represented. Clients needn’t know anything about the classes that define the product’s internal structure; such classes don’t appear in Builder’s interface.
  • It gives you finer control over the construction process- Unlike creational patterns that construct products in one shot, the Builder pattern constructs the product step by step under the director’s control. Only when the product is finished does the director retrieve it from the builder. Hence the Builder interface reflects the process of constructing the product more than other creational patterns.



Prototype

1. Intent

  • Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

2. Applicability

  • when the classes to instantiate are specified at run-time, for example, by dynamic loading; or
  • to avoid building a class hierarchy of factories that parallels the class hierarchy of products; or
  • when instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state

3. Participants

  • Prototype – declares an interface for cloning itself.
  • ConcretePrototype – implements an operation for cloning itself.
  • Client – creates a new object by asking a prototype to clone itself.

4. Structure
 

Prototype
Prototype

5. Consequences

  • Adding and removing products at run time – Prototypes let you incorporate a new concrete product class into a system simply by registering a prototypical instance with the client.
  • Specifying new objects by varying values – Highly dynamic systems let you define new behavior through object composition—by specifying values for an object’s variables, for example—and not by defining new classes

In fact, cloning a prototype is similar to instantiating a class. The Prototype pattern can greatly reduce the number of classes a system needs

  • Specifying new objects by varying structure – Many applications build objects from parts and subparts. The Prototype pattern supports this as well
  • Reduced subclassing – “Factory Method” often produces a hierarchy of Creator classes that parallels the product class hierarchy. The Prototype pattern lets you clone a prototype instead of asking a factory method to make a new object. Hence you don’t need a Creator class hierarchy at all. This benefit applies primarily to languages like C++.

Singleton

1. Intent

  • Ensure a class only has one instance, and provide a global point of access to it.

2. Applicability

  • there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
  • when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

3. Participants

  • Singleton –
    • defines an Instance operation that lets clients access its unique instance. Instance is a class operation (that is, a class method in Smalltalk and a static member function in C++).
    • may be responsible for creating its own unique instance.

4. Structure
 

Design Patterns
Singleton

5. Consequences

  • Controlled access to sole instance – Because the Singleton class encapsulates its sole instance, it can have strict control over how and when clients access it.
  • Reduced namespace – In languages that support global variables, it avoids polluting the name space with global variables that store sole instances.
  • Permits refinement of operations and representation – The Singleton class may be subclassed, and it’s easy to configure an application with an instance of this extended class at run-time.
  • Permits a variable number of instances – The pattern makes it easy to change your mind and allow more than one instance of the Singleton class.



Structural Design Patterns

  • Structural class patterns use inheritance to compose interfaces or implementations
  • Structural object patterns describe ways to compose objects to realize new functionality. The added flexibility of object composition comes from the ability to change the composition at run-time, which is impossible with static class composition.

Adapter

  • Client – collaborates with objects conforming to the Target interface.
  • Adaptee – defines an existing interface that needs adapting.
  • Adapter – adapts the interface of Adaptee to the Target interface.

1. Structure

  • Class Adapter

 

Adapter
Adapter

2. Consequences

  • Class Adapter
    • adapts Adaptee to Target by committing to a concrete Adapter class. As a consequence, a class adapter won’t work when we want to adapt a class and all its subclasses.
    • lets Adapter override some of Adaptee’s behavior, since Adapter is a subclass of Adaptee.
  • introduces only one object, and no additional pointer indirection is needed to get to the adaptee.

3. Object Adapter

  • lets a single Adapter work with many Adaptees—that is, the Adaptee itself and all of its subclasses (if any). The Adapter can also add functionality to all Adaptees at once.
  • makes it harder to override Adaptee behavior. It will require subclassing Adaptee and making Adapter refer to the subclass rather than the Adaptee itself.




Some general consequences

  • How much work does an Adapter do? – The amount of work Adapter does depends on how similar the Target interface is to Adaptee’s. There is a spectrum of possible work, from simple interface conversion—for example, changing the names of operations—to supporting an entirely different set of operations.
  • Pluggable Adapters- A class is more reusable when you minimize the assumptions other classes must make to use it. By building interface adaptation into a class, you eliminate the assumption that other classes see the same interface.
  • How much work does an Adapter do? – Two-way adapters can provide such transparency when two different clients need to view an object differently. Wherever the language supports, multiple inheritance is a viable solution in this case because the interfaces of the adapted classes are substantially different. The two-way class adapter conforms to both of the adapted classes and can work in either system.



Bridge

1. Intent

  • Decouple an abstraction from its implementation so that the two can vary independently.

2. Applicability

  • you want to avoid a permanent binding between an abstraction and its implementation. This might be the case, for example, when the implementation must be selected or switched at run-time.
  • both the abstractions and their implementations should be extensible by subclassing. In this case, the Bridge pattern lets you combine the different abstractions and implementations and extend them independently.
  • changes in the implementation of an abstraction should have no impact on clients; that is, their code should not have to be recompiled (for languages which support compilation).
  • (C++) you want to hide the implementation of an abstraction completely from clients. In C++ the representation of a class is visible in the class interface.
  • you have a proliferation of classes and where such a class hierarchy indicates the need for splitting an object into two parts.
  • you want to share an implementation among multiple objects (perhaps using reference counting), and this fact should be hidden from the client.

3. Participants

  • Abstraction –
    • defines the abstraction’s interface.
    • maintains a reference to an object of type Implementor.
  • RefinedAbstraction – Extends the interface defined by Abstraction.
  • Implementor – defines the interface for implementation classes. This interface doesn’t have to correspond exactly to Abstraction’s interface; in fact the two interfaces can be quite different. Typically the Implementor interface provides only primitive operations, and Abstraction defines higher-level operations based on these primitives.
  • ConcreteImplementor – implements the Implementor interface and defines its concrete implementation.

4. Structure
 

Design Patterns
Bridge

5. Consequences

  • Decoupling interface and implementation – An implementation is not bound permanently to an interface. The implementation of an abstraction can be configured at run-time. It’s even possible for an object to change its implementation at run-time. This decoupling encourages layering that can lead to a better-structured system. The high-level part of a system only has to know about Abstraction and Implementor.
  • Improved extensibility – You can extend the Abstraction and Implementor hierarchies independently.
  • Hiding implementation details from clients – You can shield clients from implementation details, like the sharing of implementor objects and the accompanying reference count mechanism (if any).

 

One Reply to “What are Design Patterns ? Tutorials

Comments are closed.