Showing posts with label Creational Patterns. Show all posts
Showing posts with label Creational Patterns. Show all posts

Wednesday, December 23, 2015

Design Patterns: Coffee Vending Machine

The question was asked in an interview to design a coffee vending machine.

Most importantly it is required for us to create the object with the help of creational design patterns. We would try to go through all the creational patterns which are widely known to us.

Let's start with Builder design pattern.
Builder design pattern is applied when the object constructed is huge and application would want to split the responsibility of object creation to various different objects. It can even give you the flexibility to sneak in the different implementations of a certain object based on need.

Does this DP fit to design the coffee vending machine?
Let's look over at the requirement. Coffee vending machine dispatches only few basic things i.e. various tea, various coffees, and hot water. None of the objects are really complex in nature. So it would be waste to invest so much efforts to apply builder pattern for the given problem.

Okay, let's take up another pattern i.e. Singleton design pattern.
Singleton design patterns knowing or unknowing have been in use for us. The idea behind this pattern to allow only one instance across the application. One instance must serve the need of all object requirement.

Instead analyzing this overly, we can conclude that single instance can not serve our purpose in this case. So we can not apply singleton design pattern for our application.

Moving on to Factory Abstract design pattern. (during the interview, I was using this design pattern to implement coffee vending machine)
Factory abstract design application build various different objects based on the requirement. Application would not really not know the product yet, the object created would serve the purpose of the operation. In this case application would require one class/product for each type of product type.

Does this DP fit to design the coffee vending machine?
If vending machine is used to get hot water, an object of hot water class must be returned. In this where the options could be unlimited Factory Abstract limits these options. To add another option, application would always need to introduce new class and add the application's main object which returns the output.

Could Factory Method design pattern suffice the need for this?
Based on my understanding abstract factory and factory method are almost the same. The difference lies between the responsibility of object creation. In case of factory method, object creation responsibility is designated to a factory method.

So applying this method would also be difficult in our scenario.

Let's look at the last known creational DP i.e. Prototype DP. In this design pattern we maintain a registry of object at some place and clone the object as per the need. It is very similar to on demand object creation. So in this DP also we would need to create as many classes as the options in the vending machine. Again, we would be writing way too much code for our work.

As we could not achieve the best design pattern mechanism with the help of creational design pattern. Let's move to other side of design patterns.

Let's look at the requirement in a different way.

Coffee Vending machine is using Coffee, Tea, Water, Milk, and Sugar to create all the available options. It might be needed that option might be needed to add lemon in the water and sugar to create lemon tea. In this case, we can use mix of two patterns. One abstract factory pattern and another is decorator patterns to decorate the object based on need.

Utilization of Abstract Factory pattern. Create 3 separate classes for Water, Coffee, and Tea. These 3 are the main component of the vending machine.

Now decorate the Coffee object with milk to make it milk coffee. Coffee object in itself can be utilized for espresso. Whereas in case tea, we can add various style based on the need.

milkCoffee = new Coffee(new Milk());
milkTea = new Tea(new Milk(new Masala()))
gingerTea = new Tea(new Milk(new Ginger()))
gingerMasalaTea = new Tea(new Milk(new Ginger(new Masala())))

Styling the tea and coffee can be solved with decorator pattern.

Why did we use different objects for tea and coffee?
Tea, Coffee, and Water are different products. So based on usual product understanding, we kept them separate and added styles later which are ginger to tea, masala to tea, and so on. Though it is possible to add the styles to the water to create coffee and tea also.
milkCoffee = new Water(Coffee(new Milk()));

If you think that your understanding deviates from mine. Let me know. We can discuss that in details.

Monday, December 16, 2013

Abstract Factory Design Pattern

With wider set of available options in the market, applications have to support various protocols at a specific moment in time. It becomes tedious to integrate all such vendors at one go. So to reduce the responsibility of the developer it is mandatory to share the burden with different vendors.

Abstraction has been worked wonderfully for developers and companies in the past. In this pattern too abstraction is the base.

Here, application designates the responsibility of object creation with vendor. Vendor has to write factory to instantiate the object whereas application only uses the reference of the interface.

Using this pattern a framework is defined, which produces objects that follow a general pattern and at runtime this factory is paired with any concrete factory to produce objects that follow the pattern of a certain country. In other words, the Abstract Factory is a super-factory which creates other factories (Factory of factories).

Pic taken from http://howtodoinjava.com/2012/10/29/abstract-factory-pattern-in-java/
As you can see in the image, application wants to decide certain type of cars. So application has provided carfactory interface, which delegates the responsibility on its implementing classes to implement the specific requirement.

As it is evident application has provided default factory, but there are other factories which are defined based on the region i.e. Asia, and US. It can be further divided into different segments i.e. country or class or car.

Advantage of this pattern is the delegating the creation of object on individual vendor.

Sunday, October 24, 2010

Design Pattern-2

As it was not possible to cover all the pattern in the previous post. In this post I am going to summarize the other design patterns.
Structural Patterns
Adapter: This pattern is called Wrapper pattern as well. Using this pattern, one class is made compatible with another class. For example, interface X defines 2 methods get and put. Class LegacyClass has methods implementing the required functionality but as LegacyClass can not implement newly defined interface X. So there is a need to wrap LegacyClass with Interface. Adapter pattern will provide the solution to break the ice.
Bridge: This pattern is to provide encapsulation, inheritance and abstraction to the code. In this pattern one interface is given whose implementation can be provided at lower class hierarchy keeping it hidden from the client.
Composite: Composition of no of objects to form an object. This pattern suggests to use numerous objects to create one object.
Decorator: The decorator pattern can be used to make it possible to extend (decorate) the functionality of a certain object at runtime, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.
Facade: Provide one unified interface to a set of interfaces. This unified interface works at higher level and it makes it easy to use all the interfaces at once.
Flyweight: A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory.
Private Class Data: This pattern primarily deals with encapsulation to hide the data.
Proxy: A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.

Behavioral patterns
Chain of responsibility pattern: This pattern is a source of command object and series of processing objects. Each processing object contains a set of logic that describes the types of command objects that it can handle, and how to pass off those that it cannot handle to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.
Command pattern: In this pattern object stores the information to invoke the method at later point of time. The information stored is method’s name. parameters and object to which method belongs to. There are 3 components of the pattern:
  • Client: Instantiate a command object and provide the information required to call the method at later point of time.
  • Invoker: Class which decides when to call the method.
  • Receiver: Object having method.
Interpreter pattern: Rules to identify the sentence in language. This pattern is generally used when someone needs to implement own parser.
Iterator pattern: There are aggregated data and there is need to access the data sequentially. So with exposing the internal DS, the same problem is solved by iterator patterns. Java collection API uses iterator pattern.
Mediator pattern: It is very similar facade patterns, where unified interface is exposed by extending numerous interfaces in the subsystem. This pattern is used in these circumstances.
  • Partition a system into pieces or small objects.
  • Centralize control to manipulate participating objects(a.k.a colleagues)
  • Clarify the complex relationship by providing a board committee.
  • Limit subclasses.
  • Improve objects re-usabilities.
  • Simplify object protocols.
  • The relationship between the control class and other participating classes is multidirectional.
Memento pattern: This pattern provide the ability to roll back. Here you will keep 2 states of an object one that is original i.e. anything before changes whereas other object will have latest copy with updates. This pattern is utilized in database updates.
Null Object pattern: Pattern just portrait the behavior of nothing.
Observer pattern: In this pattern a object keeps the list of its dependent, called observer. Whenever changes happened in the object its observer are notified by calling some methods. In general this pattern is used in event handling.
Weak reference pattern: A WeakReferencePattern is a structural pattern used when decoupling of an observer (a view) from an observable (a container) is necessary. A WeakReferencePattern encapsulates a reference to an object. Acquiring the reference is done through a message to the WeakReference (or WeakPointer) object. If the referenced object still exists, a real reference to it is returned. This reference is of course a temporary one.
State pattern: As the state of the object changes behavior is changed. Behavior is changes with if and else statements.

Strategy pattern: The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them. It is useful in the following situations
  • Encapsulate various algorithms to do more or less the same thing.
  • Need one of several algorithms dynamically.
  • The algorithms are exchangeable and vary independently
  • Configure a class with one of many related classes (behaviors).
  • Avoid exposing complex and algorithm-specific structures.
  • Data is transparent to the clients.
  • Reduce multiple conditional statements.
  • Provide an alternative to subclassing.
Specification pattern: In this pattern business logic can be recombined by chaining the business logic together using boolean logic.
Template method pattern: Two different components have significant similarities, but demonstrate no reuse of common interface or implementation. If a change common to both components becomes necessary, duplicate effort must be expended. Provide an abstract definition for a method or a class and redefine its behavior later or on the fly without changing its structure.
Visitor pattern: Define a new operation to deal with the classes of the elements without changing their structures. These are used in the following circumstance:
  • Add operations on a bunch of classes which have different interfaces.
  • Traverse the object structure to gather related operations
  • Easy to add new operations.
  • Crossing class hierarchies may break encapsulation.
Apart from above described patterns there are lot more patterns few of them are Single-serving visitor pattern, Hierarchical visitor pattern and Scheduled-task pattern. There are lot other than mentioned here so it is quite impossible to cover all of them. Hope this information will help all of us.


Source:

Sunday, October 17, 2010

Design Patterns

A design pattern in architecture and computer science is a formal way of documenting a solution to a design problem in a particular field of expertise.

The elements of this language are entities called patterns. Each pattern describes a problem that occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice [Christopher Alexander]


Overview
Design pattern must explain the cause of the problem and state the reasons which will help to alleviate or tackle the problems. For example a window for a room is different on the basis of different rooms but window has specific utility and characteristics. In this case window pattern should state all the problems and their suitable solutions. Along with cause and solutions it should mention the applicability of the pattern.
Design patterns were inherited in computer science from the outside world. These were introduced to provide the solution template for the recurring problems. In computer science design patterns are described as language-independent strategies for solving common object-oriented design problems. When you make a design, you should know the names of some common solutions.


Why should we use design pattern?
Design patterns can speed up the development process by providing tested, proven development paradigms. Effective software design requires considering issues that may not become visible until later in the implementation. Reusing design patterns helps to prevent subtle issues that can cause major problems and improves code readability for coders and architects familiar with the patterns. Design patterns provide general solutions, documented in a format that doesn't require specifics tied to a particular problem. In addition, patterns allow developers to communicate using well-known, well understood names for software interactions. Common design patterns can be improved over time, making them more robust than ad-hoc designs [Source].
A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.


Relationship among patterns
It is not possible to build whole software with the use of unique design pattern. We must use multiple design patterns. Along with this there are no strict rule to solve one problem with only one pattern. Several designer can use different patterns to solve same problem.
Usually:

  • Some patterns naturally fit together
  • One pattern may lead to another
  • Some patterns are similar and alternative
  • Patterns are discoverable and documentable
  • Patterns are not methods or framework
  • Patterns give you hint to solve a problem effectively [Source]
List and group of design patterns

Creational Patterns:
  • Abstract Factory – Provide an interface for creating families of related or dependent objects without specifying their concrete classes. This pattern provides the platform for independent and independence to choose own logic. It enhances the plug-ability of the software. 
  • Builder – Builds the whole object in smaller object. It is very similar to start a company. To start a company you to have a software but to build software you need lots of intermediate steps. So starting a company may include following steps. Get an office space, put furniture, hire few people to work, and start working on the product. There may be few intermediately steps but in builder all of these steps will be taken care one after another. There will not be any mix up between them.
  • Factory – In this onus of instantiating the class is with subclasses. Here a interface is provided and based on the requirement subclass is instantiated.
  • Lazy Initialization – As name suggest, don’t instantiate object until it is not needed.
  • Object Pool – In some cases it is quite an expensive process to initialize and destroy objects. To curtail down such expensive work, we create pool of objects and keep doing the task with the same pool again and again, instead of spawning new objects each time. Best example for the same is thread pool and connection pool.
  • Prototype - The prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:
    Avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
    Avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.
  • Resource Acquisition Is Initialization – This pattern is not very useful in java but for other languages it is similar de-allocation of the memory.
  • Singleton – This is the only pattern I know for a long time. In this pattern only instance of class. Whenever application tried to create a new class it request of creation is routed through one method which returns either already instantiated class or if not instantiated then it will instantiate and return the instance.
In the next section we will continue with the other type of Structural and behavioral design patterns..