Thursday, March 31, 2022

SKP's GoF Design Patterns a Day - 07 - Iterator

[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-phuket

Was going through the book ‘Head First Design Patterns’, came up with my own examples to understand them further. Try downloading the code and see if it helps you in comprehending these in a better way.
 

Iterator Pattern [Sample Code]
The need to have a handle to a collection of elements, without exposing its internal implementation is met by the Iterator Pattern. I would term this as a pure programming pattern, in its own right. By utilising this handle (Iterator), the client using the collection can easily process the same without any dependency on the internal logic.
 
Fig. 5 : Iterator (Behavioral) Design Pattern - Class and Sequence Diagram 
[Source : Wikipedia]


In the attached example, ProductMenu holds a menu or list of ProductItem. This list and its usage should be implementation agnostic to the clients. Hence, the need for a ProductIterator which implements the generic Iterator interface. The createIterator() method of ProductMenu, passes the array implementation of ProductItem to the constructor of ProductIterator.

The example can be run using ProductMenuTester.

Wednesday, March 30, 2022

SKP's GoF Design Patterns a Day - 06 - Template

[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-pattaya

Was going through the book ‘Head First Design Patterns’, came up with my own examples to understand them further. Try downloading the code and see if it helps you in comprehending these in a better way.


Template Pattern [Sample Code]
Imagine a real-world scenario where a factory is creating both aluminium nails and screws. Though the machine has to create both of them through similar processes, the way some steps are implemented may vary in each of these. When we think of such scenarios in software, we utilize the template pattern. Template pattern defines a way to re-use algorithms for various implementations with different or slightly different outcomes.
 
Fig. 4 : Template (Structural) Design Pattern - Class Diagram 
[Source : Wikipedia]


In the attached example, the abstract class SoftwareProcessor defines a general set of algorithmic steps (functions) to deliverSoftware(). This class is my template class. Since the implementation and testing phases differ in projects based on the technology stack being used, CProcessor and JavaProcessor classes adapt this algorithm for these phases. The common methods are all implemented in SoftwareProcessor and the specific ones are left as abstract.

SoftwareConsultants can be used to run this example. Try adding your own processor.

Sunday, March 27, 2022

SKP's GoF Design Patterns a Day - 05 - Adapter

[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-pattaya


Was going through the book ‘Head First Design Patterns’, came up with my own examples to understand them further. Try downloading the code and see if it helps you in comprehending these in a better way.


Adapter Pattern [Sample Code]
What can one do if he needs to use an Asian Hairdryer in a European Country, each with different socket types? I would seek an Adapter! As in real life, when we want to plug and play with similar but incompatible interfaces we use the Adapter. The Adapter adapts the Adaptee to the desired interface, by composing the Adaptee object and inheriting the desired interface or by multiple inheritance.
 
Fig. 1 : Adapter (Structural) Design Pattern - Class and Sequence Diagram 
[Source : Wikipedia]


The attached example is a real world Computer scenario, where I want to plug in an external hard drive (pre-usb era!), SeagateDrive of interface type SeagateGeneric to an incompatible computer, SamsungComputer of type Computer. SeagateGeneric provides read() and write() methods for the specified purposes, which needs to be adapted to the actual bufferData(), flushData() and purgeData() methods of the Computer. Note that there is no equivalent of purgeData(). The ideal way to handle this scenario is to throw an exception, whenever this method is invoked on the hard drive as it would do in the real world. The adapter to perform the translation in this scenario is the SeagateAdapter, which implements the Computer interface. It encapsulates a SeagateGeneric instance reference, and adapts it to the Computer interface. Whenever a bufferData() method is invoked on the Computer interface, it actual requires three invocations of read() on the SeagateGeneric implementation to match up to the Computer’s standards. These kinds of translations are done by the adapte.

PCAssembler is the main class here. Try adding your own device and its adapter to the computer.

SKP's GoF Design Patterns a Day - 04 - Abstract Factory

[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-phuket


Was going through the book ‘Head First Design Patterns’, came up with my own examples to understand them further. Try downloading the code and see if it helps you in comprehending these in a better way.


3. Abstract Factory [Sample Code]
AbstractFactory defines a template or interface for creation of similar types of objects or implementations. Usually, AbstractFactory will encapsulate a factory method or more within for actual creation of the product.
 
Fig. 6 : Abstract Factory (CreationalDesign Pattern - Class and Sequence Diagram 
[Source : Wikipedia]

 


Taking the same example as above, MobileStoreFactory instantiates the concrete instance of the abstract factory (MobileStore) based upon the variable specified, either "Nokia" (NokiaStore) or "Sony"(SonyStore). The factory is then responsible for creating the objects of similar types based upon the choice - such as "ASeries" or "BSeries" or "CSeries". The mobile is then assembled based upon this by the MobileStore. You may use MobileStoreCentre to run this example and understand the design pattern based on the output.


[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-phuket
 

Tuesday, March 22, 2022

SKP's GoF Design Patterns a Day - 03 - Factory Method

[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-phuket
#

Was going through the book ‘Head First Design Patterns’, came up with my own examples to understand them further. Try downloading the code and see if it helps you in comprehending these in a better way.

 

Factory Pattern
Factory Pattern, I am made to believe, is the most widely used and implemented pattern in software projects after the Singleton Pattern. Since Singleton is only a creational pattern at single class level, the scale of the effect of usage of Factory should be much higher. Factory Pattern deals with creation of similar type of objects and production in a centralized manner, depending on the condition or type of object requested. There are variations of the usage of factory pattern, three of which I have enlisted below:

 
1. Simple Factory [Sample Code]
The simplest factory is the one that is used to create (instantiate) a specific type of product (object) depending on a condition. The specific types of objects that can be created in a single factory are all expected to implement a single interface.

In the attached example, the factory is used to instantiate a specific type of object depending on the operating system. All the specific systems implement the System interface, which defines the common methods that the concrete class of this type should implement. SystemFactory is the factory class which provides the create() method which takes a type argument. The type argument decides which concrete factory should be instantiated.
 

2. Factory Method [Sample Code]
When there can be various families of products (objects) that which can be instantiated, but each family of these product needs to be created by a specific type of factory, we define a factory method in the base factory class. The concrete implementations of the base factory then override this method to produce concrete type of products, depending on the condition.
 
Fig. 5 : Factory Method (Creational) Design Pattern - Class Diagram 
[Source : Wikipedia]


In the example, you can notice the presence of two abstract classes, Mobile (Product) and MobileStore (Creator). One family of concrete product implementations are NokiaASeries, NokiaBSeries and NokiaCSeries to be created by the NokiaStore, which is the concrete implementation of the creator. In similar fashion another family of products such as SonyASeries, SonyBSeries and SonyCSeries are to be created by SonyStore, another concrete implementation of MobileStore. MobileStoreCentre is the main class to run this application. The createMobile() method is the abstract method (factory method) that is to be overridden by the creator implementations.

Saturday, March 19, 2022

SKP's GoF Design Patterns a Day - 02 - Singleton

[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-phuket


Was going through the book ‘Head First Design Patterns’, came up with my own examples to understand them further. Try downloading the code and see if it helps you in comprehending these in a better way.
 

Singleton Pattern
Singleton Pattern defines a way to maintain only single instance of a class in the entire execution of a program/application and to provide a uniform way to access it. There are numerous methods which exist in which this pattern can be implemented. I have explained three most common scenarios here:
 
Fig. 3 : Singleton (Creational) Design Pattern - Class Diagram 
[Source : Wikipedia]

 

1. Eager Singleton [Sample Code]
The simplest singleton is the one in which the instance is created at class-load time, and stored in a static instance variable. A static getter method is then used to get this instance, when required. The instantiation of an object earlier than its first use might not be a recommended approach.

In the given example, MediaContract (Main Thread) works on an instance of the ProductionHouse (Singleton). The Singleton is instantiated at class-load time and maintained in the private static instance variable. getInstance() in ProductionHouse helps in retrieving the instance.

 
2. Thread-Safe Singleton (Most Common) [Sample Code]
To overcome the above drawback, the recommended approach is to instantiate the object at the first access time and also to make it thread-safe to prevent concurrent thread instantiation. The disadvantage of this method is poorer performance, as the method is synchronized.

As in the earlier example, the classes are MediaContract (Main Thread) and ProductionHouse (Singleton). getInstance() method is synchronized and the instance is created only if it is null.

 
3. Double-Checked Locking [Sample Code]
The disadvantage mentioned above can be critical for a highly accessed object in an application. To better this, the scope of the synchronized block is reduced to affect only the first access. This again has some disadvantages. I recommend reading on Initialization on Demand Holder Idiom.

The example remains the same, the difference being in the reduced scope of synchronisation within the getInstance() method and also that it affects only the first access and not subsequent accesses.
 

Friday, March 18, 2022

SKP's GoF Design Patterns a Day - 01 - Observer

[GitHub Repository for Code Samples]
 

Was going through the book ‘Head First Design Patterns’, came up with my own examples to understand them further. Try downloading the code and see if it helps you in comprehending these in a better way.



Observer Pattern [Sample Code]
Observer Pattern, as the name suggests, is used in scenarios when updates need to be done at multiple points (Observers) depending on changes in state at another place (Subject). Each of the Observers has to register themselves with the Subject, individually. The Subject should also provide method which allows the Observers to remove themselves. Registered Observers are informed of changes in state through a notify method, usually.
 
Fig. 1 : Observer (Behavioral) Design Pattern - Class and Sequence Diagram 
[Source : Wikipedia]


The provided example is that of a StockBroker application, which involves maintenance of various types of financial information. Subject is the interface in the application which provides a template for the Observed class. StockData is the concrete implementation of Subject and provided implementation of addObserver(), removeObserver() and notifyObservers(). Additionally, it maintains a list of registered observers. IncomeHandler, InvestmentHandler and PortfolioHandler are the various observers used to maintain income, investment and portfolio of a specific StockBroker. All these depend on the constantly fluctuating values of stocks. They are specifically interested in the stockSymbol, stockValue and stockUnits of each individual stock. Each of the observers implements the interface Observer. The Observer interface provide the update() method, which is implemented by each of these concrete classes.

Use StockBroker.java to run the application, Try adding your own observer to this application. Also, you can try picking up these values from a live web service and then writing a custom observer which depends on this.