Вы находитесь на странице: 1из 10

Page |1

Developer To Developer: Design Patterns - Creational Patterns


Ajay Kumar Singh, Nagarro. Design Patterns are generic solutions to common Software Design related scenarios. Over the period of time Software Developers and Architects have faced similar problems, so they documented the designs which can be used to handle these commonly faced scenarios. Knowing these patterns will not only save your time, it will also provide you with tried and tested solution for a problem. Therefore prime focus of this document is to introduce a Software Developer to the world of design patterns in the simplest and fastest possible way.

Introduction Most important design concept of world is 'KIS' - Keep It Simple. Yes before we get deeper into patterns and learn them, let's talk about the basics first. While designing a Software Solution, we should never forget two targets, first is to keep our code as simple as possible, and second is to remember that we need to provide an efficiently working solution to the Client. These two points may look too trivial to talk about, but believe me it's very easy to see 'Resume Driven Designs' around you, where an engineer would fancy himself as a cool Architect and design such a complex system which would not just make the code difficult to implement and maintain, but it will also increase project cost so much that economically it becomes unprofitable to implement that design. So the targets we will try to achieve here with a design pattern is to keep our code clean, modular and readable and make sure that classes aren't tightly coupled.

Categories As we talked earlier, patterns are just solutions for a known scenario in Software Development.

Define Patterns Long ago during my one class of C language when I was teaching Do-While loop, suddenly my one student asked me for the Definition of Do-While Loop and I really didnt know how to respond to it. I still dont know definitions of most of the things but one thing I know is that many people love to get a cool and complex looking definition for everything. So I have included a small definition of every design pattern.

Page |2 Therefore based on the different types of scenarios we categories Design Patterns in 3 categories .

Creational Patterns Abstract Factory Builder Factory Method Prototype Singleton

Creates an instance of several families of classes Separates object construction from its representation Creates an instance of several derived classes A fully initialized instance to be copied or cloned A class of which only a single instance can exist

Structural Patterns Match interfaces of different classes Adapter Separates an objects interface from its implementation Bridge A tree structure of simple and composite objects Composite Add responsibilities to objects dynamically Decorator A single class that represents an entire subsystem Facade A fine-grained instance used for efficient sharing Flyweight An object representing another object Proxy Behavioral Patterns Chain of Resp. Command Interpreter Iterator Mediator Memento Observer State Strategy Template Method Visitor

A way of passing a request between a chain of objects Encapsulate a command request as an object A way to include language elements in a program Sequentially access the elements of a collection Defines simplified communication between classes Capture and restore an object's internal state A way of notifying change to a number of classes Alter an object's behaviour when its state changes Encapsulates an algorithm inside a class Defer the exact steps of an algorithm to a subclass Defines a new operation to a class without change

Here in this Document we will be discussing only Creational Patterns. Other categories will be covered in separate documents.

Page |3

1) Creational Design Patterns These patterns provide different ways of creating Classes and Objects, that's why they are called creational patterns. The creational patterns aim to separate a system from how its objects are created, composed, and represented. Following is a list of Design Patterns which come under this category -

A) FACTORY As the name suggests we create a Factory which can create different types of objects. What type of object we need we can tell that to factory and we will get that type of object. Factory is one of the most simple Design Pattern. Here we will be understand it using example of an Office package. Imagine that our requirement is to create different types of documents using our Office Software Package, all documents here will share common IDocument interface. Define Factory Factory Pattern defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. Factory Design -

So we will start with a IDocument interface which will have the basic properties of a document.
public interface IDocument

Now lets create our class for Word Documents and Excel Documents using this interface, lets call it MyWord and MyExcel class.
class MyWord: IDocument class MyExcel:IDocument

Page |4 After creating classes for our different document types, we can now a DocumentFactory class to start creating different type of objects on demand.
public class DocumentFactory

This class will have a method which will return objects based on the type we specify.
public IDocument GetDocument(string docType)

{
//Here if docType is Word return object of MyWord if docType is Excel //return MyExcel

} This is a very simple example to show the logic which needs to be used, definitely you can improve this code, such as we can define some enum for different document types instead of hard coding the string. After getting all classes in place, we can go ahead and create our first object using this Factory DocumentFactory simpleFactory=new DocumentFactory(); IDocument myDocument = simpleFactory.GetDocument("Word");

Additional Resources http://javapapers.com/design-patterns/factory-method-pattern/ http://sourcemaking.com/design_patterns/factory_method http://www.oodesign.com/factory-pattern.html

B) ABSTRACT FACTORY Abstract Factory pattern also uses the concept used in simple Factory pattern, however instead of providing one factory for creating different types of objects, it provides different types of Factories for specialized object creations. Now imagine that our client has changed the requirements and now he wants our Office Package to create different types of text documents and not just one simple My Word type of document. Similarly we want different types of Spreadsheet documents also. Therefore now we need to create three types of Text documents - Text Only document, Rich Text document with Rich Text support and our favourite MyWord type document with full feature (like MS Word). Our Spreadsheet module has also evolved now and it allows you to create two types of documentsCSV Documents and My Excel documents.

Page |5 Define Abstract Factory Provides an interface for creating families of related or dependent objects without specifying their concrete classes. Design Abstract Factory -

Our IDocument interface will remain same because we still need all document to follow basics of a document public interface IDocument

Now we need to define different Document classes class PlainText:IDocument class RichText:IDocument class MyWord: IDocument Similarly for Spreadsheets class MyExcel:IDocument class CSVSheet:IDocument

Now here comes the difference from Factory pattern, this time we will not be creating single factory class with Create method. We will be creating a Factory interface which can be inherited by specialized Factory Classes. public interface IDocumentFactory { IDocument CreateDocument(string docType); }

This base IDocumentFactory can also be an abstract class, all we want to make sure is that, here we do not create conceret class which can directly be used.

Page |6

class WordFactory : IDocumentFactory { } class SpreadsheetFactory:IDocumentFactory { }

Our design is complete, so now its time to get it working IDocumentFactory WordProcessor= new WordFactory(); IDocumentFactory SpreadSheetProcessor = new SpreadsheetFactory(); //We can add one more layer of abstraction here, for creating different Factories we can create a Static Factory Class with Static Create method, //it can return us the type of Factory we need. IDocument myRichTextDoc = WordProcessor.CreateDocument("RichText"); IDocument myCSVSpreadsheet = SpreadSheetProcessor.CreateDocument("CSV");

Additional Resources http://sourcemaking.com/design_patterns/abstract_factory http://javapapers.com/design-patterns/abstract-factory-pattern/ http://www.oodesign.com/abstract-factory-pattern.html

C) BUILDER Builder pattern focuses on defining different Steps. Each of these steps will construct a part of the final object which we are creating. When these steps are followed in correct sequence we will have our final product created. Define Builder Separates the construction of a complex object from its representation so that the same construction process can create different representations. Design Builder -

Page |7 Lets get this pattern into design. Here we will try to create a Holiday Planner software. We all love to go on Holidays, but based on our preference we choose different holiday duration (depending on our leaves), different types of Tickets and different Hotels. So we will start with Holiday class, we can also define an interface for our Holiday class, but here we are keeping it simple class Holiday { public void setDuration(int duration) { } public void setTicket(string ticketDetails) { } public void setHotel(string hotel) { } }

Now we need builders for different types of holiday packages, so we will create HolidayBuilder interface first.
public interface IHolidayBuilder { //We will be calling setDuration, setTicket and setHotel from these //builder methods. void buildDuration(); void buildTicket(); void buildHotel(); Holiday getHoliday(); }

Now its time to make few types of concrete Holiday Packages by using our abstract IHolidayBuilder interface
class MauritiusTrip: IHolidayBuilder { //create a new Holiday object here, call build methods //finally return our fully defined Holiday object } class EuropeTrip: IHolidayBuilder { //create a new Holiday object here, call build methods //finally return our fully defined Holiday object }

After getting different trips in hand, we can define our Holiday planner which will use Holiday Builder to plan a trip

Page |8
class HolidayPlanner { //A Constructor method public void PlanHoliday(IHolidayBuilder myTrip) { myTrip.buildDuration(); myTrip.buildTicket(); myTrip. buildHotel(); } }

Finally get the software working. We can plan any trip now for our next holiday
HolidayPlanner ourHolidayPlanner = new WordFactory(); IHolidayBuilder MauritiusTripBuilder = new MauritiusTrip (); IHolidayBuilder EuropeTripBuilder = new EuropeTrip ();

ourHolidayPlanner.PlanHoliday (MauritiusTripBuilder); Holiday myNextMauritiusTrip = MauritiusTripBuilder.getHoliday(); ourHolidayPlanner.PlanHoliday (EuropeTripBuilder); Holiday myNextEuropeTrip = EuropeTripBuilder.getHoliday();

Additional Resources http://www.oodesign.com/builder-pattern.html http://sourcemaking.com/design_patterns/builder http://javapapers.com/design-patterns/builder-pattern/

D) PROTOTYPE Prototype design pattern is a very simple design pattern. All you need to have is a Clone() method in your class. This method will provide a copy of current object with all values. Benefit of this pattern is that if you want to extend functionality of any existing object, all you need to do is to Clone it and modify the values you need to change.

Define Prototype Specifies the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

Page |9 Design Prototype -

public interface Prototype { public abstract Object clone ( ); } public class ConcretePrototype : Prototype { public Object clone() { } }

Now finally implement it.


ConcretePrototype obj1= new ConcretePrototype (); ConcretePrototype obj2 = (ConcretePrototype)obj1.clone();

Additional Resources http://www.oodesign.com/prototype-pattern.html http://sourcemaking.com/design_patterns/prototype http://javapapers.com/design-patterns/prototype-pattern/

P a g e | 10

E) SINGLETON
There are scenarios when you need only one instance/object of a class to exist. The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made private. Define Singleton Ensures a class has only one instance, and provide a global point of access to it. Design Prototype -

Here is the sample code showing implementation of simplest Singleton. This code is just for showing logic, and it can be made more complex like we can make it thread safe. But the basic concept remains same for Singleton. public class Singleton { private static Singleton instance = new Singleton();
private Singleton() {} public static Singleton getInstance() { return instance; } }

Additional Resources http://www.oodesign.com/singleton-pattern.html http://sourcemaking.com/design_patterns/singleton http://javapapers.com/design-patterns/singleton-pattern/

Вам также может понравиться