What is Design pattern and how to implement them

Date: 19/12/2019

Introduction

The article is will not explain something about a specific language. So other than the code block, I will talk about design patterns.

Design patterns are crafting the communication between bunches of code. In OOPS, you can scale, incorporate more functionality. Generally, we may want to have more than one class to perform a certain task. In this case, if you don’t have an appropriate pattern, you will finally get more bugs that can be avoided easily, scalability issues and maintenance nightmare for future developers because every source code will be updated as time goes.

Here, I will just explain the Command pattern with javascript which is about switching on and off of a light. There are more design patterns out there. Some patterns of outdated. So please try avoiding them.

As a newbie to programming, if you are working on a new project, you may be blindsided how to or where to these kinds of patterns. You can search for use cases of the pattern on the internet. Try to ask yourself and find your own. Because that’s is where you are truly harnessing your programming skill.

Example

In this example, you will learn how to perform the task of swiching light and storing the actions. Along the way, we will use inheritance (passing one class object into another).

class Switch {
  constructor() {
    this._commands = [];
  }

  storeAndExecute(command) {
    this._commands.push(command);
    command.execute();
  }
}

class Light {
  turnOn() { console.log('on') }
  turnOff() { console.log('off') }
}

class PressDownCommand {
  constructor(light) {
    this._light = light;
  }

  execute() {
    this._light.turnOff();
  }
}

class PressUpCommand {
  constructor(light) {
    this._light = light;
  }

  execute() {
    this._light.turnOn();
  }
}

var light = new Light();
var switchUp = new PressUpCommand(light);
var switchDown = new PressDownCommand(light);
var s = new Switch();

s.storeAndExecute(switchUp);
s.storeAndExecute(switchDown);

With the last two lines of codes, we perform one switch on and one switch off. If you print s.commands, you will find the actions we perform. That’s it. You have learned something new. Great!.

Conclusion

In the early ’90s, there’s a book released called Design Pattern. Please check out those too. There is more pattern available out there. Personally, I also recommend Wikipedia for those different patterns. Because you can see the available in different languages. And also reliable one in terms of out of date issues. Because as a newbie, you can’t recognize the good or bad one. I hope you like it. Please comment on the content if you find anything incorrect.

Please feel free to share if you find it useful. Thank you.

References

Leave a Reply