Design patterns

I rarely see design patterns as requirement in job postings and this both surprises and concerns me. I can't explain (or even learn) all the design patterns in one post, but as a person who has spent some time on this matter, i can explain some of the 14 design patterns that i have covered in my Udemy course. The purpose of the course is to simplify the concept and make it easy to understand and embrace. Because design patterns is already a high level abstract subject. In this post, i will introduce and briefly explain. You can find the course here.

What is a design pattern

Algorithm is the word when programmers use when they don't want to explain what they did. Design pattern is the concept used by programmers when they do want to explain what they did. In other words, it is the solution approach to tackle any kind of problem during the development, it is not the solution itself. Design pattern will not tell you what code you will write, it tells you the architecture of the code.

It's history is mostly well known, so i am skipping that part. Right now you must be asking the question, why are there design patterns. Programming is basically the storage, access and the process of the information inside the computer. We write codes to achieve this and these codes starts interacting with each other in time. At this point, you will need some sort of management and common language to be able to conceptualize it. Whether is is programming or not. This language is gathered around 3 main priciples. Creational, Behavioral and Structural. The first one is about the creation of the information, the second one is about the behaviour of it and the third one is about the structure of this information. It is still so abstract isn't it. Then let the examples roll in and let me save the philosophy for later. I have included the key codes for the design patterns in the list below. But the reason to write these codes and the history of it is the subject of the course of course :)

Builder

One of the creational patterns, builder pattern, makes it easy to code the necessary construction steps of an object. The example of this pattern is the human body. This way, we can create a bodybuilder class :) Instead of writing a huge constructor or tens of lines of code to construct a human body, we can create a builder class whic manipulates the body object inside it. This style of code is called fluent code. I have met with this style with JavaFX and i loved it back in the day. The code below shows the result of this kind of builder class. Builder is a cumulative approach which adds more properties as you call methods sequantially. Eventually, it returns the body. We put together a body with 2 arms, 2 ears and 2 eyes like a Lego.

		
Body body = new BodyBuilder().setArms( 2 ).setEars( 2 ).setEyes( 2 ).build();
		
	

Factory

I have seen different interperetations of the factory design pattern. But i could not find a better suited example for this pattern than a, you know, factory :) Thic factory can produce cars and bikes. It handles the construction process inside, which is more complex than the builder, thus making it easy to order. The purpose is to simplify the object creation process and make it easy to understand. For example, if you want a car, all you need to specify is the doors count. If you want a bike, you need to give front and rear tyre configurations. This way, you don't have to know how to make a car or a bike. I ahve utilies the generics of java and created the example below.

		
public class VehicleFactory
{
    public static Vehicle buildVehicle( Class<Car> C, int doorsCount )
    {
        Vehicle vehicle = new Car( doorsCount );
        return vehicle;
    }
    public static Vehicle buildVehicle( Class<Bike> B, String frontTyre, String rearTyre )
    {
        Vehicle vehicle = new Bike( frontTyre, rearTyre );
        return vehicle;
    }
}
		
	

Visitor

The patterns before this were interested in the creation of the objects and their storage in the memory. Now let's take a look at the behavioural patterns. These patterns are interested in the interaction between the objects and their behaviour of course. My example for the visitor design pattern is the postman. Postman gets a result from each residenct he visits, in form of delivery is success or not. But the residence he is visiting can be an apartment or a farm or a mansion. Instead of writing a giant postman class to be able to interact with all sorts of residence, we will inherit the residences from same interface and make them accept the postman and response according to their rules or exceptions. The example code below will make it more clear. Keep in mind, the logic inside the isHome method can be very complex. This is why it is implemented inside the residences, instead of the postman.

		
class Postman
{
    private ArrayList<Boolean> delivered = new ArrayList<>();
    public void deliver( Farm farm )
    {
        delivered.add( farm.isHome() );
    }
	public void deliver( Apartment apartment )
    {
        delivered.add( apartment.isHome() );
    }
}
		
	

		
public class Apartment implements Residence
{
    @Override
    public void acceptMail( Postman postman )
    {
        postman.deliver( this );
    }
    public boolean isHome()
    {
        return new Random().nextInt( 5 ) != 3;
    }
}
		
	

Strategy

The exact meaning of the behavioural design patterns is the strategy design pattern. According to this pattern, an object should be able to behave differently while it is alive, without re-coding or recreation. Does this mean a class must have lots of functions inside? No. We will implement this on the dependency injection concept. My example for this is an actor. You give the genre to the actor and he/she acts according to it. In real life those people already know how to act under different genres but as a memorable design pattern example, i think it suits well. The actor class below has a method to change the genre. This method takes the genre from the same interface, thus enabling the actor to act accordingly.

		
public class Actor
{
    private Genre genre;
    public void setGenre( Genre genre )
    {
        this.genre = genre;
    }
    public void act()
    {
        genre.act();
    }
}
		
	

Chain of Responsibility

The matter that we resolve in this pattern is one function being carried out by a sequence of objects. In other words, everyone should mind their own bussiness. We use this phrase a lot in real life but my example for this pattern might be a bit nauseating :) Our digestive system is literaly a chain of responsibility. There is some digestion in mouth, and then stomach and intestines. The rest is not about digesting so it is not out concern now :) In this pattern, every object forwards the object inside to the next one itself while also deciding how or when to deliver it. We only set the order of the chain from outside, just like a linkedlist. We are making sure that it's not going to come back to mouth after the stomach.

		
public static void main( String[] args )
{
	Mouth mouth = new Mouth();
	Stomach stomach = new Stomach();
	Intestine intestine = new Intestine();
	mouth.setNextDigestor( stomach );
	stomach.setNextDigestor( intestine );
	mouth.digest( "Hamburger" );
}
		
	

		
public class Mouth implements Digestor
{
    private Digestor nextDigestor;
    public void setNextDigestor( Digestor nextDigestor )
    {
        this.nextDigestor = nextDigestor;
    }
    @Override
    public void digest( String food )
    {
        System.out.println( "Mouth is digesting " + food );
        if ( nextDigestor != null )
        {
            nextDigestor.digest( food );
        }
    }
}
		
	

Bridge

Bridge design pattern is the connector between 2 complex structures, probably interfaces. It manages the interaction between variable implemantations, which would be so hard to implement otherwise. An example of this can be the public relations person. This person can understand the bosses working methods and answers the questions from the reporters or social media. This person can also connect different bosses and different reporters. Because the boss and the reporter is just an interface.

		
class PublicRelations
{
    private CompanyManager companyManager;
    private ArrayList<Reporter> reporters;
    public PublicRelations()
    {
        companyManager = new Manager();
        reporters = new ArrayList<>();
        reporters.add( new SmartReporter() );
        reporters.add( new DumbReporter() );
    }
    public void connect()
    {
        String question = reporters.get( 0 ).askQuestion();
        reporters.get( 0 ).getAnswer( companyManager.makeStatement( 0 ) );
        question = reporters.get( 1 ).askQuestion();
        reporters.get( 1 ).getAnswer( companyManager.makeStatement( 1 ) );
        reporters.get( 0 ).getAnswer( companyManager.makeStatement( 2 ) );
        reporters.get( 1 ).getAnswer( companyManager.makeStatement( 2 ) );
    }
}
		
	

		
public interface CompanyManager
{
    public void work();
    public String makeStatement( int i );
}
public interface Reporter
{
    public String askQuestion();
    public void getAnswer( String message );
}
		
	

Facade

The command design pattern is yet another structural design pattern which looks similar to command design pattern which aims to simplify and bring functionalities together. But this one is interested in the structure rather than the interaction. You might have lots of abstractions in your code. But when you want to use them, you may not know all the necessary logic to use them. So you write another class in front of them to utilize all these abstractions inside. An example of this is the managers assistant. Assistants job is to make the bosses job easier by simplifying the complex logic of different type of workers. It looks like a bridge but the complexity in this situation is on the workers side only. And the purpose is to make all these easily usable. The example below is an assistans whic can work with classes constructed from Work and Finance interface.

		
public class Assistant
{
    private Finance finance;
    private ArrayList<Work> works = new ArrayList<>();
    public void setFinance( Finance finance )
    {
        this.finance = finance;
    }
    public void addWork( Work work )
    {
        works.add( work );
    }
    public String getReport()
    {
        String report = "";
        for ( Work work : works )
        {
            report += work.details() + "\n";
        }
        return report;
    }
    public void getFinancialSituation()
    {
        finance.financialSituation();
        finance.financialForecast();
    }
}
		
	

Summary

There must be a design pattern story of the project before it begins. I associate this with the process of building a house.

  • 1st step is to decide the building blocks. In other words, the creational design pattern. Is it going to be concrete or steel or bricks or etc.
  • 2nd step is to decide what kind of house is it going to be and to implement it. In other words, structural design patterns. This step is the most important one. You will have to analyze the bussiness deeply and try to forecast its future.
  • 3rd step is to put people inside the house and let them live and behave. In other words, behavioural design patterns. At this stage you will realize if the desicions you made in the the second step was right or wrong.

Design patterns is actually a programming conversation language. This is why it is really hard to simplify it. In order to understand some patterns, you may need at least basic object oriented programming principles. Because some of the patterns are build upon object oriented approach and only available in those languages. There are other patterns and some comparisons in the course i have prepared on Udemy. Let me put the link here again and conclude with this words: If you're doing it right, programming is an art. See you at the next post :)


Leave a comment