{"id":49342190,"url":"https://github.com/nilbuild/design-patterns-for-humans","last_synced_at":"2026-04-28T19:00:40.523Z","repository":{"id":37376202,"uuid":"82227585","full_name":"nilbuild/design-patterns-for-humans","owner":"nilbuild","description":"An ultra-simplified explanation to design patterns","archived":false,"fork":false,"pushed_at":"2024-12-02T04:54:48.000Z","size":149,"stargazers_count":47771,"open_issues_count":16,"forks_count":5509,"subscribers_count":1195,"default_branch":"master","last_synced_at":"2026-04-26T10:27:28.686Z","etag":null,"topics":["architecture","computer-science","design-patterns","engineering","principles","software-engineering"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nilbuild.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["kamranahmedse"]}},"created_at":"2017-02-16T21:24:39.000Z","updated_at":"2026-04-26T09:59:12.000Z","dependencies_parsed_at":"2024-01-15T09:03:25.709Z","dependency_job_id":"4b6b5fc2-3d4c-43c3-8f0a-75df30c8d29f","html_url":"https://github.com/nilbuild/design-patterns-for-humans","commit_stats":{"total_commits":139,"total_committers":45,"mean_commits":3.088888888888889,"dds":0.3525179856115108,"last_synced_commit":"ba92c416a750ed9a287985d62c57cd34fefca0cc"},"previous_names":["nilbuild/design-patterns-for-humans"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/nilbuild/design-patterns-for-humans","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilbuild%2Fdesign-patterns-for-humans","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilbuild%2Fdesign-patterns-for-humans/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilbuild%2Fdesign-patterns-for-humans/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilbuild%2Fdesign-patterns-for-humans/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nilbuild","download_url":"https://codeload.github.com/nilbuild/design-patterns-for-humans/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilbuild%2Fdesign-patterns-for-humans/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32394478,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-28T14:34:11.604Z","status":"ssl_error","status_checked_at":"2026-04-28T14:32:37.009Z","response_time":56,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["architecture","computer-science","design-patterns","engineering","principles","software-engineering"],"created_at":"2026-04-27T05:00:28.965Z","updated_at":"2026-04-28T19:00:40.514Z","avatar_url":"https://github.com/nilbuild.png","language":null,"readme":"\u003cbr\u003e\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"./.github/banner.svg\" height=\"150px\" /\u003e\n\u003c/p\u003e\n\n***\n\n\u003cp align=\"center\"\u003e\n🎉 Ultra-simplified explanation to design patterns! 🎉\n\u003c/p\u003e\n\u003cp align=\"center\"\u003e\nA topic that can easily make anyone's mind wobble. Here I try to make them stick in to your\u003cbr\u003e mind (and maybe mine) by explaining them in the \u003ci\u003esimplest\u003c/i\u003e way possible.\n\u003c/p\u003e\n\n***\n\n\u003csub\u003eCheck out my [other project](http://roadmap.sh) and say \"hi\" on [Twitter](https://twitter.com/kamrify).\u003c/sub\u003e\n\n\u003cbr\u003e\n\n|[Creational Design Patterns](#creational-design-patterns)|[Structural Design Patterns](#structural-design-patterns)|[Behavioral Design Patterns](#behavioral-design-patterns)|\n|:-|:-|:-|\n|[Simple Factory](#-simple-factory)|[Adapter](#-adapter)|[Chain of Responsibility](#-chain-of-responsibility)|\n|[Factory Method](#-factory-method)|[Bridge](#-bridge)|[Command](#-command)|\n|[Abstract Factory](#-abstract-factory)|[Composite](#-composite)|[Iterator](#-iterator)|\n|[Builder](#-builder)|[Decorator](#-decorator)|[Mediator](#-mediator)|\n|[Prototype](#-prototype)|[Facade](#-facade)|[Memento](#-memento)|\n|[Singleton](#-singleton)|[Flyweight](#-flyweight)|[Observer](#-observer)|\n||[Proxy](#-proxy)|[Visitor](#-visitor)|\n|||[Strategy](#-strategy)|\n|||[State](#-state)|\n|||[Template Method](#-template-method)|\n\n\u003cbr\u003e\n\nIntroduction\n=================\n\nDesign patterns are solutions to recurring problems; **guidelines on how to tackle certain problems**. They are not classes, packages or libraries that you can plug into your application and wait for the magic to happen. These are, rather, guidelines on how to tackle certain problems in certain situations.\n\n\u003e Design patterns are solutions to recurring problems; guidelines on how to tackle certain problems\n\nWikipedia describes them as\n\n\u003e In software engineering, a software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code. It is a description or template for how to solve a problem that can be used in many different situations.\n\n⚠️ Be Careful\n-----------------\n- Design patterns are not a silver bullet to all your problems.\n- Do not try to force them; bad things are supposed to happen, if done so. \n- Keep in mind that design patterns are solutions **to** problems, not solutions **finding** problems; so don't overthink.\n- If used in a correct place in a correct manner, they can prove to be a savior; or else they can result in a horrible mess of a code.\n\n\u003e Also note that the code samples below are in PHP-7, however this shouldn't stop you because the concepts are same anyways.\n\nTypes of Design Patterns\n-----------------\n\n* [Creational](#creational-design-patterns)\n* [Structural](#structural-design-patterns)\n* [Behavioral](#behavioral-design-patterns)\n\nCreational Design Patterns\n==========================\n\nIn plain words\n\u003e Creational patterns are focused towards how to instantiate an object or group of related objects.\n\nWikipedia says\n\u003e In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.\n\n * [Simple Factory](#-simple-factory)\n * [Factory Method](#-factory-method)\n * [Abstract Factory](#-abstract-factory)\n * [Builder](#-builder)\n * [Prototype](#-prototype)\n * [Singleton](#-singleton)\n\n🏠 Simple Factory\n--------------\nReal world example\n\u003e Consider, you are building a house and you need doors. You can either put on your carpenter clothes, bring some wood, glue, nails and all the tools required to build the door and start building it in your house or you can simply call the factory and get the built door delivered to you so that you don't need to learn anything about the door making or to deal with the mess that comes with making it.\n\nIn plain words\n\u003e Simple factory simply generates an instance for client without exposing any instantiation logic to the client\n\nWikipedia says\n\u003e In object-oriented programming (OOP), a factory is an object for creating other objects – formally a factory is a function or method that returns objects of a varying prototype or class from some method call, which is assumed to be \"new\".\n\n**Programmatic Example**\n\nFirst of all we have a door interface and the implementation\n```php\ninterface Door\n{\n    public function getWidth(): float;\n    public function getHeight(): float;\n}\n\nclass WoodenDoor implements Door\n{\n    protected $width;\n    protected $height;\n\n    public function __construct(float $width, float $height)\n    {\n        $this-\u003ewidth = $width;\n        $this-\u003eheight = $height;\n    }\n\n    public function getWidth(): float\n    {\n        return $this-\u003ewidth;\n    }\n\n    public function getHeight(): float\n    {\n        return $this-\u003eheight;\n    }\n}\n```\nThen we have our door factory that makes the door and returns it\n```php\nclass DoorFactory\n{\n    public static function makeDoor($width, $height): Door\n    {\n        return new WoodenDoor($width, $height);\n    }\n}\n```\nAnd then it can be used as\n```php\n// Make me a door of 100x200\n$door = DoorFactory::makeDoor(100, 200);\n\necho 'Width: ' . $door-\u003egetWidth();\necho 'Height: ' . $door-\u003egetHeight();\n\n// Make me a door of 50x100\n$door2 = DoorFactory::makeDoor(50, 100);\n```\n\n**When to Use?**\n\nWhen creating an object is not just a few assignments and involves some logic, it makes sense to put it in a dedicated factory instead of repeating the same code everywhere.\n\n🏭 Factory Method\n--------------\n\nReal world example\n\u003e Consider the case of a hiring manager. It is impossible for one person to interview for each of the positions. Based on the job opening, she has to decide and delegate the interview steps to different people.\n\nIn plain words\n\u003e It provides a way to delegate the instantiation logic to child classes.\n\nWikipedia says\n\u003e In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.\n\n **Programmatic Example**\n\nTaking our hiring manager example above. First of all we have an interviewer interface and some implementations for it\n\n```php\ninterface Interviewer\n{\n    public function askQuestions();\n}\n\nclass Developer implements Interviewer\n{\n    public function askQuestions()\n    {\n        echo 'Asking about design patterns!';\n    }\n}\n\nclass CommunityExecutive implements Interviewer\n{\n    public function askQuestions()\n    {\n        echo 'Asking about community building';\n    }\n}\n```\n\nNow let us create our `HiringManager`\n\n```php\nabstract class HiringManager\n{\n\n    // Factory method\n    abstract protected function makeInterviewer(): Interviewer;\n\n    public function takeInterview()\n    {\n        $interviewer = $this-\u003emakeInterviewer();\n        $interviewer-\u003easkQuestions();\n    }\n}\n\n```\nNow any child can extend it and provide the required interviewer\n```php\nclass DevelopmentManager extends HiringManager\n{\n    protected function makeInterviewer(): Interviewer\n    {\n        return new Developer();\n    }\n}\n\nclass MarketingManager extends HiringManager\n{\n    protected function makeInterviewer(): Interviewer\n    {\n        return new CommunityExecutive();\n    }\n}\n```\nand then it can be used as\n\n```php\n$devManager = new DevelopmentManager();\n$devManager-\u003etakeInterview(); // Output: Asking about design patterns\n\n$marketingManager = new MarketingManager();\n$marketingManager-\u003etakeInterview(); // Output: Asking about community building.\n```\n\n**When to use?**\n\nUseful when there is some generic processing in a class but the required sub-class is dynamically decided at runtime. Or putting it in other words, when the client doesn't know what exact sub-class it might need.\n\n🔨 Abstract Factory\n----------------\n\nReal world example\n\u003e Extending our door example from Simple Factory. Based on your needs you might get a wooden door from a wooden door shop, iron door from an iron shop or a PVC door from the relevant shop. Plus you might need a guy with different kind of specialities to fit the door, for example a carpenter for wooden door, welder for iron door etc. As you can see there is a dependency between the doors now, wooden door needs carpenter, iron door needs a welder etc.\n\nIn plain words\n\u003e A factory of factories; a factory that groups the individual but related/dependent factories together without specifying their concrete classes.\n\nWikipedia says\n\u003e The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes\n\n**Programmatic Example**\n\nTranslating the door example above. First of all we have our `Door` interface and some implementation for it\n\n```php\ninterface Door\n{\n    public function getDescription();\n}\n\nclass WoodenDoor implements Door\n{\n    public function getDescription()\n    {\n        echo 'I am a wooden door';\n    }\n}\n\nclass IronDoor implements Door\n{\n    public function getDescription()\n    {\n        echo 'I am an iron door';\n    }\n}\n```\nThen we have some fitting experts for each door type\n\n```php\ninterface DoorFittingExpert\n{\n    public function getDescription();\n}\n\nclass Welder implements DoorFittingExpert\n{\n    public function getDescription()\n    {\n        echo 'I can only fit iron doors';\n    }\n}\n\nclass Carpenter implements DoorFittingExpert\n{\n    public function getDescription()\n    {\n        echo 'I can only fit wooden doors';\n    }\n}\n```\n\nNow we have our abstract factory that would let us make family of related objects i.e. wooden door factory would create a wooden door and wooden door fitting expert and iron door factory would create an iron door and iron door fitting expert\n```php\ninterface DoorFactory\n{\n    public function makeDoor(): Door;\n    public function makeFittingExpert(): DoorFittingExpert;\n}\n\n// Wooden factory to return carpenter and wooden door\nclass WoodenDoorFactory implements DoorFactory\n{\n    public function makeDoor(): Door\n    {\n        return new WoodenDoor();\n    }\n\n    public function makeFittingExpert(): DoorFittingExpert\n    {\n        return new Carpenter();\n    }\n}\n\n// Iron door factory to get iron door and the relevant fitting expert\nclass IronDoorFactory implements DoorFactory\n{\n    public function makeDoor(): Door\n    {\n        return new IronDoor();\n    }\n\n    public function makeFittingExpert(): DoorFittingExpert\n    {\n        return new Welder();\n    }\n}\n```\nAnd then it can be used as\n```php\n$woodenFactory = new WoodenDoorFactory();\n\n$door = $woodenFactory-\u003emakeDoor();\n$expert = $woodenFactory-\u003emakeFittingExpert();\n\n$door-\u003egetDescription();  // Output: I am a wooden door\n$expert-\u003egetDescription(); // Output: I can only fit wooden doors\n\n// Same for Iron Factory\n$ironFactory = new IronDoorFactory();\n\n$door = $ironFactory-\u003emakeDoor();\n$expert = $ironFactory-\u003emakeFittingExpert();\n\n$door-\u003egetDescription();  // Output: I am an iron door\n$expert-\u003egetDescription(); // Output: I can only fit iron doors\n```\n\nAs you can see the wooden door factory has encapsulated the `carpenter` and the `wooden door` also iron door factory has encapsulated the `iron door` and `welder`. And thus it had helped us make sure that for each of the created door, we do not get a wrong fitting expert.   \n\n**When to use?**\n\nWhen there are interrelated dependencies with not-that-simple creation logic involved\n\n👷 Builder\n--------------------------------------------\nReal world example\n\u003e Imagine you are at Hardee's and you order a specific deal, lets say, \"Big Hardee\" and they hand it over to you without *any questions*; this is the example of simple factory. But there are cases when the creation logic might involve more steps. For example you want a customized Subway deal, you have several options in how your burger is made e.g what bread do you want? what types of sauces would you like? What cheese would you want? etc. In such cases builder pattern comes to the rescue.\n\nIn plain words\n\u003e Allows you to create different flavors of an object while avoiding constructor pollution. Useful when there could be several flavors of an object. Or when there are a lot of steps involved in creation of an object.\n\nWikipedia says\n\u003e The builder pattern is an object creation software design pattern with the intentions of finding a solution to the telescoping constructor anti-pattern.\n\nHaving said that let me add a bit about what telescoping constructor anti-pattern is. At one point or the other we have all seen a constructor like below:\n\n```php\npublic function __construct($size, $cheese = true, $pepperoni = true, $tomato = false, $lettuce = true)\n{\n}\n```\n\nAs you can see; the number of constructor parameters can quickly get out of hand and it might become difficult to understand the arrangement of parameters. Plus this parameter list could keep on growing if you would want to add more options in future. This is called telescoping constructor anti-pattern.\n\n**Programmatic Example**\n\nThe sane alternative is to use the builder pattern. First of all we have our burger that we want to make\n\n```php\nclass Burger\n{\n    protected $size;\n\n    protected $cheese = false;\n    protected $pepperoni = false;\n    protected $lettuce = false;\n    protected $tomato = false;\n\n    public function __construct(BurgerBuilder $builder)\n    {\n        $this-\u003esize = $builder-\u003esize;\n        $this-\u003echeese = $builder-\u003echeese;\n        $this-\u003epepperoni = $builder-\u003epepperoni;\n        $this-\u003elettuce = $builder-\u003elettuce;\n        $this-\u003etomato = $builder-\u003etomato;\n    }\n}\n```\n\nAnd then we have the builder\n\n```php\nclass BurgerBuilder\n{\n    public $size;\n\n    public $cheese = false;\n    public $pepperoni = false;\n    public $lettuce = false;\n    public $tomato = false;\n\n    public function __construct(int $size)\n    {\n        $this-\u003esize = $size;\n    }\n\n    public function addPepperoni()\n    {\n        $this-\u003epepperoni = true;\n        return $this;\n    }\n\n    public function addLettuce()\n    {\n        $this-\u003elettuce = true;\n        return $this;\n    }\n\n    public function addCheese()\n    {\n        $this-\u003echeese = true;\n        return $this;\n    }\n\n    public function addTomato()\n    {\n        $this-\u003etomato = true;\n        return $this;\n    }\n\n    public function build(): Burger\n    {\n        return new Burger($this);\n    }\n}\n```\nAnd then it can be used as:\n\n```php\n$burger = (new BurgerBuilder(14))\n                    -\u003eaddPepperoni()\n                    -\u003eaddLettuce()\n                    -\u003eaddTomato()\n                    -\u003ebuild();\n```\n\n**When to use?**\n\nWhen there could be several flavors of an object and to avoid the constructor telescoping. The key difference from the factory pattern is that; factory pattern is to be used when the creation is a one step process while builder pattern is to be used when the creation is a multi step process.\n\n🐑 Prototype\n------------\nReal world example\n\u003e Remember dolly? The sheep that was cloned! Lets not get into the details but the key point here is that it is all about cloning\n\nIn plain words\n\u003e Create object based on an existing object through cloning.\n\nWikipedia says\n\u003e The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects.\n\nIn short, it allows you to create a copy of an existing object and modify it to your needs, instead of going through the trouble of creating an object from scratch and setting it up.\n\n**Programmatic Example**\n\nIn PHP, it can be easily done using `clone`\n\n```php\nclass Sheep\n{\n    protected $name;\n    protected $category;\n\n    public function __construct(string $name, string $category = 'Mountain Sheep')\n    {\n        $this-\u003ename = $name;\n        $this-\u003ecategory = $category;\n    }\n\n    public function setName(string $name)\n    {\n        $this-\u003ename = $name;\n    }\n\n    public function getName()\n    {\n        return $this-\u003ename;\n    }\n\n    public function setCategory(string $category)\n    {\n        $this-\u003ecategory = $category;\n    }\n\n    public function getCategory()\n    {\n        return $this-\u003ecategory;\n    }\n}\n```\nThen it can be cloned like below\n```php\n$original = new Sheep('Jolly');\necho $original-\u003egetName(); // Jolly\necho $original-\u003egetCategory(); // Mountain Sheep\n\n// Clone and modify what is required\n$cloned = clone $original;\n$cloned-\u003esetName('Dolly');\necho $cloned-\u003egetName(); // Dolly\necho $cloned-\u003egetCategory(); // Mountain sheep\n```\n\nAlso you could use the magic method `__clone` to modify the cloning behavior.\n\n**When to use?**\n\nWhen an object is required that is similar to existing object or when the creation would be expensive as compared to cloning.\n\n💍 Singleton\n------------\nReal world example\n\u003e There can only be one president of a country at a time. The same president has to be brought to action, whenever duty calls. President here is singleton.\n\nIn plain words\n\u003e Ensures that only one object of a particular class is ever created.\n\nWikipedia says\n\u003e In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.\n\nSingleton pattern is actually considered an anti-pattern and overuse of it should be avoided. It is not necessarily bad and could have some valid use-cases but should be used with caution because it introduces a global state in your application and change to it in one place could affect in the other areas and it could become pretty difficult to debug. The other bad thing about them is it makes your code tightly coupled plus mocking the singleton could be difficult.\n\n**Programmatic Example**\n\nTo create a singleton, make the constructor private, disable cloning, disable extension and create a static variable to house the instance\n```php\nfinal class President\n{\n    private static $instance;\n\n    private function __construct()\n    {\n        // Hide the constructor\n    }\n\n    public static function getInstance(): President\n    {\n        if (!self::$instance) {\n            self::$instance = new self();\n        }\n\n        return self::$instance;\n    }\n\n    private function __clone()\n    {\n        // Disable cloning\n    }\n\n    private function __wakeup()\n    {\n        // Disable unserialize\n    }\n}\n```\nThen in order to use\n```php\n$president1 = President::getInstance();\n$president2 = President::getInstance();\n\nvar_dump($president1 === $president2); // true\n```\n\nStructural Design Patterns\n==========================\nIn plain words\n\u003e Structural patterns are mostly concerned with object composition or in other words how the entities can use each other. Or yet another explanation would be, they help in answering \"How to build a software component?\"\n\nWikipedia says\n\u003e In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.\n\n * [Adapter](#-adapter)\n * [Bridge](#-bridge)\n * [Composite](#-composite)\n * [Decorator](#-decorator)\n * [Facade](#-facade)\n * [Flyweight](#-flyweight)\n * [Proxy](#-proxy)\n\n🔌 Adapter\n-------\nReal world example\n\u003e Consider that you have some pictures in your memory card and you need to transfer them to your computer. In order to transfer them you need some kind of adapter that is compatible with your computer ports so that you can attach memory card to your computer. In this case card reader is an adapter.\n\u003e Another example would be the famous power adapter; a three legged plug can't be connected to a two pronged outlet, it needs to use a power adapter that makes it compatible with the two pronged outlet.\n\u003e Yet another example would be a translator translating words spoken by one person to another\n\nIn plain words\n\u003e Adapter pattern lets you wrap an otherwise incompatible object in an adapter to make it compatible with another class.\n\nWikipedia says\n\u003e In software engineering, the adapter pattern is a software design pattern that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code.\n\n**Programmatic Example**\n\nConsider a game where there is a hunter and he hunts lions.\n\nFirst we have an interface `Lion` that all types of lions have to implement\n\n```php\ninterface Lion\n{\n    public function roar();\n}\n\nclass AfricanLion implements Lion\n{\n    public function roar()\n    {\n    }\n}\n\nclass AsianLion implements Lion\n{\n    public function roar()\n    {\n    }\n}\n```\nAnd hunter expects any implementation of `Lion` interface to hunt.\n```php\nclass Hunter\n{\n    public function hunt(Lion $lion)\n    {\n        $lion-\u003eroar();\n    }\n}\n```\n\nNow let's say we have to add a `WildDog` in our game so that hunter can hunt that also. But we can't do that directly because dog has a different interface. To make it compatible for our hunter, we will have to create an adapter that is compatible\n\n```php\n// This needs to be added to the game\nclass WildDog\n{\n    public function bark()\n    {\n    }\n}\n\n// Adapter around wild dog to make it compatible with our game\nclass WildDogAdapter implements Lion\n{\n    protected $dog;\n\n    public function __construct(WildDog $dog)\n    {\n        $this-\u003edog = $dog;\n    }\n\n    public function roar()\n    {\n        $this-\u003edog-\u003ebark();\n    }\n}\n```\nAnd now the `WildDog` can be used in our game using `WildDogAdapter`.\n\n```php\n$wildDog = new WildDog();\n$wildDogAdapter = new WildDogAdapter($wildDog);\n\n$hunter = new Hunter();\n$hunter-\u003ehunt($wildDogAdapter);\n```\n\n🚡 Bridge\n------\nReal world example\n\u003e Consider you have a website with different pages and you are supposed to allow the user to change the theme. What would you do? Create multiple copies of each of the pages for each of the themes or would you just create separate theme and load them based on the user's preferences? Bridge pattern allows you to do the second i.e.\n\n![With and without the bridge pattern](https://cloud.githubusercontent.com/assets/11269635/23065293/33b7aea0-f515-11e6-983f-98823c9845ee.png)\n\nIn Plain Words\n\u003e Bridge pattern is about preferring composition over inheritance. Implementation details are pushed from a hierarchy to another object with a separate hierarchy.\n\nWikipedia says\n\u003e The bridge pattern is a design pattern used in software engineering that is meant to \"decouple an abstraction from its implementation so that the two can vary independently\"\n\n**Programmatic Example**\n\nTranslating our WebPage example from above. Here we have the `WebPage` hierarchy\n\n```php\ninterface WebPage\n{\n    public function __construct(Theme $theme);\n    public function getContent();\n}\n\nclass About implements WebPage\n{\n    protected $theme;\n\n    public function __construct(Theme $theme)\n    {\n        $this-\u003etheme = $theme;\n    }\n\n    public function getContent()\n    {\n        return \"About page in \" . $this-\u003etheme-\u003egetColor();\n    }\n}\n\nclass Careers implements WebPage\n{\n    protected $theme;\n\n    public function __construct(Theme $theme)\n    {\n        $this-\u003etheme = $theme;\n    }\n\n    public function getContent()\n    {\n        return \"Careers page in \" . $this-\u003etheme-\u003egetColor();\n    }\n}\n```\nAnd the separate theme hierarchy\n```php\n\ninterface Theme\n{\n    public function getColor();\n}\n\nclass DarkTheme implements Theme\n{\n    public function getColor()\n    {\n        return 'Dark Black';\n    }\n}\nclass LightTheme implements Theme\n{\n    public function getColor()\n    {\n        return 'Off white';\n    }\n}\nclass AquaTheme implements Theme\n{\n    public function getColor()\n    {\n        return 'Light blue';\n    }\n}\n```\nAnd both the hierarchies\n```php\n$darkTheme = new DarkTheme();\n\n$about = new About($darkTheme);\n$careers = new Careers($darkTheme);\n\necho $about-\u003egetContent(); // \"About page in Dark Black\";\necho $careers-\u003egetContent(); // \"Careers page in Dark Black\";\n```\n\n🌿 Composite\n-----------------\n\nReal world example\n\u003e Every organization is composed of employees. Each of the employees has the same features i.e. has a salary, has some responsibilities, may or may not report to someone, may or may not have some subordinates etc.\n\nIn plain words\n\u003e Composite pattern lets clients treat the individual objects in a uniform manner.\n\nWikipedia says\n\u003e In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects is to be treated in the same way as a single instance of an object. The intent of a composite is to \"compose\" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.\n\n**Programmatic Example**\n\nTaking our employees example from above. Here we have different employee types\n\n```php\ninterface Employee\n{\n    public function __construct(string $name, float $salary);\n    public function getName(): string;\n    public function setSalary(float $salary);\n    public function getSalary(): float;\n    public function getRoles(): array;\n}\n\nclass Developer implements Employee\n{\n    protected $salary;\n    protected $name;\n    protected $roles;\n    \n    public function __construct(string $name, float $salary)\n    {\n        $this-\u003ename = $name;\n        $this-\u003esalary = $salary;\n    }\n\n    public function getName(): string\n    {\n        return $this-\u003ename;\n    }\n\n    public function setSalary(float $salary)\n    {\n        $this-\u003esalary = $salary;\n    }\n\n    public function getSalary(): float\n    {\n        return $this-\u003esalary;\n    }\n\n    public function getRoles(): array\n    {\n        return $this-\u003eroles;\n    }\n}\n\nclass Designer implements Employee\n{\n    protected $salary;\n    protected $name;\n    protected $roles;\n\n    public function __construct(string $name, float $salary)\n    {\n        $this-\u003ename = $name;\n        $this-\u003esalary = $salary;\n    }\n\n    public function getName(): string\n    {\n        return $this-\u003ename;\n    }\n\n    public function setSalary(float $salary)\n    {\n        $this-\u003esalary = $salary;\n    }\n\n    public function getSalary(): float\n    {\n        return $this-\u003esalary;\n    }\n\n    public function getRoles(): array\n    {\n        return $this-\u003eroles;\n    }\n}\n```\n\nThen we have an organization which consists of several different types of employees\n\n```php\nclass Organization\n{\n    protected $employees;\n\n    public function addEmployee(Employee $employee)\n    {\n        $this-\u003eemployees[] = $employee;\n    }\n\n    public function getNetSalaries(): float\n    {\n        $netSalary = 0;\n\n        foreach ($this-\u003eemployees as $employee) {\n            $netSalary += $employee-\u003egetSalary();\n        }\n\n        return $netSalary;\n    }\n}\n```\n\nAnd then it can be used as\n\n```php\n// Prepare the employees\n$john = new Developer('John Doe', 12000);\n$jane = new Designer('Jane Doe', 15000);\n\n// Add them to organization\n$organization = new Organization();\n$organization-\u003eaddEmployee($john);\n$organization-\u003eaddEmployee($jane);\n\necho \"Net salaries: \" . $organization-\u003egetNetSalaries(); // Net Salaries: 27000\n```\n\n☕ Decorator\n-------------\n\nReal world example\n\n\u003e Imagine you run a car service shop offering multiple services. Now how do you calculate the bill to be charged? You pick one service and dynamically keep adding to it the prices for the provided services till you get the final cost. Here each type of service is a decorator.\n\nIn plain words\n\u003e Decorator pattern lets you dynamically change the behavior of an object at run time by wrapping them in an object of a decorator class.\n\nWikipedia says\n\u003e In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern.\n\n**Programmatic Example**\n\nLets take coffee for example. First of all we have a simple coffee implementing the coffee interface\n\n```php\ninterface Coffee\n{\n    public function getCost();\n    public function getDescription();\n}\n\nclass SimpleCoffee implements Coffee\n{\n    public function getCost()\n    {\n        return 10;\n    }\n\n    public function getDescription()\n    {\n        return 'Simple coffee';\n    }\n}\n```\nWe want to make the code extensible to allow options to modify it if required. Lets make some add-ons (decorators)\n```php\nclass MilkCoffee implements Coffee\n{\n    protected $coffee;\n\n    public function __construct(Coffee $coffee)\n    {\n        $this-\u003ecoffee = $coffee;\n    }\n\n    public function getCost()\n    {\n        return $this-\u003ecoffee-\u003egetCost() + 2;\n    }\n\n    public function getDescription()\n    {\n        return $this-\u003ecoffee-\u003egetDescription() . ', milk';\n    }\n}\n\nclass WhipCoffee implements Coffee\n{\n    protected $coffee;\n\n    public function __construct(Coffee $coffee)\n    {\n        $this-\u003ecoffee = $coffee;\n    }\n\n    public function getCost()\n    {\n        return $this-\u003ecoffee-\u003egetCost() + 5;\n    }\n\n    public function getDescription()\n    {\n        return $this-\u003ecoffee-\u003egetDescription() . ', whip';\n    }\n}\n\nclass VanillaCoffee implements Coffee\n{\n    protected $coffee;\n\n    public function __construct(Coffee $coffee)\n    {\n        $this-\u003ecoffee = $coffee;\n    }\n\n    public function getCost()\n    {\n        return $this-\u003ecoffee-\u003egetCost() + 3;\n    }\n\n    public function getDescription()\n    {\n        return $this-\u003ecoffee-\u003egetDescription() . ', vanilla';\n    }\n}\n```\n\nLets make a coffee now\n\n```php\n$someCoffee = new SimpleCoffee();\necho $someCoffee-\u003egetCost(); // 10\necho $someCoffee-\u003egetDescription(); // Simple Coffee\n\n$someCoffee = new MilkCoffee($someCoffee);\necho $someCoffee-\u003egetCost(); // 12\necho $someCoffee-\u003egetDescription(); // Simple Coffee, milk\n\n$someCoffee = new WhipCoffee($someCoffee);\necho $someCoffee-\u003egetCost(); // 17\necho $someCoffee-\u003egetDescription(); // Simple Coffee, milk, whip\n\n$someCoffee = new VanillaCoffee($someCoffee);\necho $someCoffee-\u003egetCost(); // 20\necho $someCoffee-\u003egetDescription(); // Simple Coffee, milk, whip, vanilla\n```\n\n📦 Facade\n----------------\n\nReal world example\n\u003e How do you turn on the computer? \"Hit the power button\" you say! That is what you believe because you are using a simple interface that computer provides on the outside, internally it has to do a lot of stuff to make it happen. This simple interface to the complex subsystem is a facade.\n\nIn plain words\n\u003e Facade pattern provides a simplified interface to a complex subsystem.\n\nWikipedia says\n\u003e A facade is an object that provides a simplified interface to a larger body of code, such as a class library.\n\n**Programmatic Example**\n\nTaking our computer example from above. Here we have the computer class\n\n```php\nclass Computer\n{\n    public function getElectricShock()\n    {\n        echo \"Ouch!\";\n    }\n\n    public function makeSound()\n    {\n        echo \"Beep beep!\";\n    }\n\n    public function showLoadingScreen()\n    {\n        echo \"Loading..\";\n    }\n\n    public function bam()\n    {\n        echo \"Ready to be used!\";\n    }\n\n    public function closeEverything()\n    {\n        echo \"Bup bup bup buzzzz!\";\n    }\n\n    public function sooth()\n    {\n        echo \"Zzzzz\";\n    }\n\n    public function pullCurrent()\n    {\n        echo \"Haaah!\";\n    }\n}\n```\nHere we have the facade\n```php\nclass ComputerFacade\n{\n    protected $computer;\n\n    public function __construct(Computer $computer)\n    {\n        $this-\u003ecomputer = $computer;\n    }\n\n    public function turnOn()\n    {\n        $this-\u003ecomputer-\u003egetElectricShock();\n        $this-\u003ecomputer-\u003emakeSound();\n        $this-\u003ecomputer-\u003eshowLoadingScreen();\n        $this-\u003ecomputer-\u003ebam();\n    }\n\n    public function turnOff()\n    {\n        $this-\u003ecomputer-\u003ecloseEverything();\n        $this-\u003ecomputer-\u003epullCurrent();\n        $this-\u003ecomputer-\u003esooth();\n    }\n}\n```\nNow to use the facade\n```php\n$computer = new ComputerFacade(new Computer());\n$computer-\u003eturnOn(); // Ouch! Beep beep! Loading.. Ready to be used!\n$computer-\u003eturnOff(); // Bup bup buzzz! Haah! Zzzzz\n```\n\n🍃 Flyweight\n---------\n\nReal world example\n\u003e Did you ever have fresh tea from some stall? They often make more than one cup that you demanded and save the rest for any other customer so to save the resources e.g. gas etc. Flyweight pattern is all about that i.e. sharing.\n\nIn plain words\n\u003e It is used to minimize memory usage or computational expenses by sharing as much as possible with similar objects.\n\nWikipedia says\n\u003e In computer programming, flyweight is a software design pattern. 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.\n\n**Programmatic example**\n\nTranslating our tea example from above. First of all we have tea types and tea maker\n\n```php\n// Anything that will be cached is flyweight.\n// Types of tea here will be flyweights.\nclass KarakTea\n{\n}\n\n// Acts as a factory and saves the tea\nclass TeaMaker\n{\n    protected $availableTea = [];\n\n    public function make($preference)\n    {\n        if (empty($this-\u003eavailableTea[$preference])) {\n            $this-\u003eavailableTea[$preference] = new KarakTea();\n        }\n\n        return $this-\u003eavailableTea[$preference];\n    }\n}\n```\n\nThen we have the `TeaShop` which takes orders and serves them\n\n```php\nclass TeaShop\n{\n    protected $orders;\n    protected $teaMaker;\n\n    public function __construct(TeaMaker $teaMaker)\n    {\n        $this-\u003eteaMaker = $teaMaker;\n    }\n\n    public function takeOrder(string $teaType, int $table)\n    {\n        $this-\u003eorders[$table] = $this-\u003eteaMaker-\u003emake($teaType);\n    }\n\n    public function serve()\n    {\n        foreach ($this-\u003eorders as $table =\u003e $tea) {\n            echo \"Serving tea to table# \" . $table;\n        }\n    }\n}\n```\nAnd it can be used as below\n\n```php\n$teaMaker = new TeaMaker();\n$shop = new TeaShop($teaMaker);\n\n$shop-\u003etakeOrder('less sugar', 1);\n$shop-\u003etakeOrder('more milk', 2);\n$shop-\u003etakeOrder('without sugar', 5);\n\n$shop-\u003eserve();\n// Serving tea to table# 1\n// Serving tea to table# 2\n// Serving tea to table# 5\n```\n\n🎱 Proxy\n-------------------\nReal world example\n\u003e Have you ever used an access card to go through a door? There are multiple options to open that door i.e. it can be opened either using access card or by pressing a button that bypasses the security. The door's main functionality is to open but there is a proxy added on top of it to add some functionality. Let me better explain it using the code example below.\n\nIn plain words\n\u003e Using the proxy pattern, a class represents the functionality of another class.\n\nWikipedia says\n\u003e A proxy, in its most general form, is a class functioning as an interface to something else. A proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes. Use of the proxy can simply be forwarding to the real object, or can provide additional logic. In the proxy extra functionality can be provided, for example caching when operations on the real object are resource intensive, or checking preconditions before operations on the real object are invoked.\n\n**Programmatic Example**\n\nTaking our security door example from above. Firstly we have the door interface and an implementation of door\n\n```php\ninterface Door\n{\n    public function open();\n    public function close();\n}\n\nclass LabDoor implements Door\n{\n    public function open()\n    {\n        echo \"Opening lab door\";\n    }\n\n    public function close()\n    {\n        echo \"Closing the lab door\";\n    }\n}\n```\nThen we have a proxy to secure any doors that we want\n```php\nclass SecuredDoor implements Door\n{\n    protected $door;\n\n    public function __construct(Door $door)\n    {\n        $this-\u003edoor = $door;\n    }\n\n    public function open($password)\n    {\n        if ($this-\u003eauthenticate($password)) {\n            $this-\u003edoor-\u003eopen();\n        } else {\n            echo \"Big no! It ain't possible.\";\n        }\n    }\n\n    public function authenticate($password)\n    {\n        return $password === '$ecr@t';\n    }\n\n    public function close()\n    {\n        $this-\u003edoor-\u003eclose();\n    }\n}\n```\nAnd here is how it can be used\n```php\n$door = new SecuredDoor(new LabDoor());\n$door-\u003eopen('invalid'); // Big no! It ain't possible.\n\n$door-\u003eopen('$ecr@t'); // Opening lab door\n$door-\u003eclose(); // Closing lab door\n```\nYet another example would be some sort of data-mapper implementation. For example, I recently made an ODM (Object Data Mapper) for MongoDB using this pattern where I wrote a proxy around mongo classes while utilizing the magic method `__call()`. All the method calls were proxied to the original mongo class and result retrieved was returned as it is but in case of `find` or `findOne` data was mapped to the required class objects and the object was returned instead of `Cursor`.\n\nBehavioral Design Patterns\n==========================\n\nIn plain words\n\u003e It is concerned with assignment of responsibilities between the objects. What makes them different from structural patterns is they don't just specify the structure but also outline the patterns for message passing/communication between them. Or in other words, they assist in answering \"How to run a behavior in software component?\"\n\nWikipedia says\n\u003e In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.\n\n* [Chain of Responsibility](#-chain-of-responsibility)\n* [Command](#-command)\n* [Iterator](#-iterator)\n* [Mediator](#-mediator)\n* [Memento](#-memento)\n* [Observer](#-observer)\n* [Visitor](#-visitor)\n* [Strategy](#-strategy)\n* [State](#-state)\n* [Template Method](#-template-method)\n\n🔗 Chain of Responsibility\n-----------------------\n\nReal world example\n\u003e For example, you have three payment methods (`A`, `B` and `C`) setup in your account; each having a different amount in it. `A` has 100 USD, `B` has 300 USD and `C` having 1000 USD and the preference for payments is chosen as `A` then `B` then `C`. You try to purchase something that is worth 210 USD. Using Chain of Responsibility, first of all account `A` will be checked if it can make the purchase, if yes purchase will be made and the chain will be broken. If not, request will move forward to account `B` checking for amount if yes chain will be broken otherwise the request will keep forwarding till it finds the suitable handler. Here `A`, `B` and `C` are links of the chain and the whole phenomenon is Chain of Responsibility.\n\nIn plain words\n\u003e It helps building a chain of objects. Request enters from one end and keeps going from object to object till it finds the suitable handler.\n\nWikipedia says\n\u003e In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain.\n\n**Programmatic Example**\n\nTranslating our account example above. First of all we have a base account having the logic for chaining the accounts together and some accounts\n\n```php\nabstract class Account\n{\n    protected $successor;\n    protected $balance;\n\n    public function setNext(Account $account)\n    {\n        $this-\u003esuccessor = $account;\n    }\n\n    public function pay(float $amountToPay)\n    {\n        if ($this-\u003ecanPay($amountToPay)) {\n            echo sprintf('Paid %s using %s' . PHP_EOL, $amountToPay, get_called_class());\n        } elseif ($this-\u003esuccessor) {\n            echo sprintf('Cannot pay using %s. Proceeding ..' . PHP_EOL, get_called_class());\n            $this-\u003esuccessor-\u003epay($amountToPay);\n        } else {\n            throw new Exception('None of the accounts have enough balance');\n        }\n    }\n\n    public function canPay($amount): bool\n    {\n        return $this-\u003ebalance \u003e= $amount;\n    }\n}\n\nclass Bank extends Account\n{\n    protected $balance;\n\n    public function __construct(float $balance)\n    {\n        $this-\u003ebalance = $balance;\n    }\n}\n\nclass Paypal extends Account\n{\n    protected $balance;\n\n    public function __construct(float $balance)\n    {\n        $this-\u003ebalance = $balance;\n    }\n}\n\nclass Bitcoin extends Account\n{\n    protected $balance;\n\n    public function __construct(float $balance)\n    {\n        $this-\u003ebalance = $balance;\n    }\n}\n```\n\nNow let's prepare the chain using the links defined above (i.e. Bank, Paypal, Bitcoin)\n\n```php\n// Let's prepare a chain like below\n//      $bank-\u003e$paypal-\u003e$bitcoin\n//\n// First priority bank\n//      If bank can't pay then paypal\n//      If paypal can't pay then bit coin\n\n$bank = new Bank(100);          // Bank with balance 100\n$paypal = new Paypal(200);      // Paypal with balance 200\n$bitcoin = new Bitcoin(300);    // Bitcoin with balance 300\n\n$bank-\u003esetNext($paypal);\n$paypal-\u003esetNext($bitcoin);\n\n// Let's try to pay using the first priority i.e. bank\n$bank-\u003epay(259);\n\n// Output will be\n// ==============\n// Cannot pay using bank. Proceeding ..\n// Cannot pay using paypal. Proceeding ..:\n// Paid 259 using Bitcoin!\n```\n\n👮 Command\n-------\n\nReal world example\n\u003e A generic example would be you ordering food at a restaurant. You (i.e. `Client`) ask the waiter (i.e. `Invoker`) to bring some food (i.e. `Command`) and waiter simply forwards the request to Chef (i.e. `Receiver`) who has the knowledge of what and how to cook.\n\u003e Another example would be you (i.e. `Client`) switching on (i.e. `Command`) the television (i.e. `Receiver`) using a remote control (`Invoker`).\n\nIn plain words\n\u003e Allows you to encapsulate actions in objects. The key idea behind this pattern is to provide the means to decouple client from receiver.\n\nWikipedia says\n\u003e In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.\n\n**Programmatic Example**\n\nFirst of all we have the receiver that has the implementation of every action that could be performed\n```php\n// Receiver\nclass Bulb\n{\n    public function turnOn()\n    {\n        echo \"Bulb has been lit\";\n    }\n\n    public function turnOff()\n    {\n        echo \"Darkness!\";\n    }\n}\n```\nthen we have an interface that each of the commands are going to implement and then we have a set of commands\n```php\ninterface Command\n{\n    public function execute();\n    public function undo();\n    public function redo();\n}\n\n// Command\nclass TurnOn implements Command\n{\n    protected $bulb;\n\n    public function __construct(Bulb $bulb)\n    {\n        $this-\u003ebulb = $bulb;\n    }\n\n    public function execute()\n    {\n        $this-\u003ebulb-\u003eturnOn();\n    }\n\n    public function undo()\n    {\n        $this-\u003ebulb-\u003eturnOff();\n    }\n\n    public function redo()\n    {\n        $this-\u003eexecute();\n    }\n}\n\nclass TurnOff implements Command\n{\n    protected $bulb;\n\n    public function __construct(Bulb $bulb)\n    {\n        $this-\u003ebulb = $bulb;\n    }\n\n    public function execute()\n    {\n        $this-\u003ebulb-\u003eturnOff();\n    }\n\n    public function undo()\n    {\n        $this-\u003ebulb-\u003eturnOn();\n    }\n\n    public function redo()\n    {\n        $this-\u003eexecute();\n    }\n}\n```\nThen we have an `Invoker` with whom the client will interact to process any commands\n```php\n// Invoker\nclass RemoteControl\n{\n    public function submit(Command $command)\n    {\n        $command-\u003eexecute();\n    }\n}\n```\nFinally let's see how we can use it in our client\n```php\n$bulb = new Bulb();\n\n$turnOn = new TurnOn($bulb);\n$turnOff = new TurnOff($bulb);\n\n$remote = new RemoteControl();\n$remote-\u003esubmit($turnOn); // Bulb has been lit!\n$remote-\u003esubmit($turnOff); // Darkness!\n```\n\nCommand pattern can also be used to implement a transaction based system. Where you keep maintaining the history of commands as soon as you execute them. If the final command is successfully executed, all good otherwise just iterate through the history and keep executing the `undo` on all the executed commands.\n\n➿ Iterator\n--------\n\nReal world example\n\u003e An old radio set will be a good example of iterator, where user could start at some channel and then use next or previous buttons to go through the respective channels. Or take an example of MP3 player or a TV set where you could press the next and previous buttons to go through the consecutive channels or in other words they all provide an interface to iterate through the respective channels, songs or radio stations.  \n\nIn plain words\n\u003e It presents a way to access the elements of an object without exposing the underlying presentation.\n\nWikipedia says\n\u003e In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.\n\n**Programmatic example**\n\nIn PHP it is quite easy to implement using SPL (Standard PHP Library). Translating our radio stations example from above. First of all we have `RadioStation`\n\n```php\nclass RadioStation\n{\n    protected $frequency;\n\n    public function __construct(float $frequency)\n    {\n        $this-\u003efrequency = $frequency;\n    }\n\n    public function getFrequency(): float\n    {\n        return $this-\u003efrequency;\n    }\n}\n```\nThen we have our iterator\n\n```php\nuse Countable;\nuse Iterator;\n\nclass StationList implements Countable, Iterator\n{\n    /** @var RadioStation[] $stations */\n    protected $stations = [];\n\n    /** @var int $counter */\n    protected $counter;\n\n    public function addStation(RadioStation $station)\n    {\n        $this-\u003estations[] = $station;\n    }\n\n    public function removeStation(RadioStation $toRemove)\n    {\n        $toRemoveFrequency = $toRemove-\u003egetFrequency();\n        $this-\u003estations = array_filter($this-\u003estations, function (RadioStation $station) use ($toRemoveFrequency) {\n            return $station-\u003egetFrequency() !== $toRemoveFrequency;\n        });\n    }\n\n    public function count(): int\n    {\n        return count($this-\u003estations);\n    }\n\n    public function current(): RadioStation\n    {\n        return $this-\u003estations[$this-\u003ecounter];\n    }\n\n    public function key()\n    {\n        return $this-\u003ecounter;\n    }\n\n    public function next()\n    {\n        $this-\u003ecounter++;\n    }\n\n    public function rewind()\n    {\n        $this-\u003ecounter = 0;\n    }\n\n    public function valid(): bool\n    {\n        return isset($this-\u003estations[$this-\u003ecounter]);\n    }\n}\n```\nAnd then it can be used as\n```php\n$stationList = new StationList();\n\n$stationList-\u003eaddStation(new RadioStation(89));\n$stationList-\u003eaddStation(new RadioStation(101));\n$stationList-\u003eaddStation(new RadioStation(102));\n$stationList-\u003eaddStation(new RadioStation(103.2));\n\nforeach($stationList as $station) {\n    echo $station-\u003egetFrequency() . PHP_EOL;\n}\n\n$stationList-\u003eremoveStation(new RadioStation(89)); // Will remove station 89\n```\n\n👽 Mediator\n========\n\nReal world example\n\u003e A general example would be when you talk to someone on your mobile phone, there is a network provider sitting between you and them and your conversation goes through it instead of being directly sent. In this case network provider is mediator.\n\nIn plain words\n\u003e Mediator pattern adds a third party object (called mediator) to control the interaction between two objects (called colleagues). It helps reduce the coupling between the classes communicating with each other. Because now they don't need to have the knowledge of each other's implementation.\n\nWikipedia says\n\u003e In software engineering, the mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program's running behavior.\n\n**Programmatic Example**\n\nHere is the simplest example of a chat room (i.e. mediator) with users (i.e. colleagues) sending messages to each other.\n\nFirst of all, we have the mediator i.e. the chat room\n\n```php\ninterface ChatRoomMediator \n{\n    public function showMessage(User $user, string $message);\n}\n\n// Mediator\nclass ChatRoom implements ChatRoomMediator\n{\n    public function showMessage(User $user, string $message)\n    {\n        $time = date('M d, y H:i');\n        $sender = $user-\u003egetName();\n\n        echo $time . '[' . $sender . ']:' . $message;\n    }\n}\n```\n\nThen we have our users i.e. colleagues\n```php\nclass User {\n    protected $name;\n    protected $chatMediator;\n\n    public function __construct(string $name, ChatRoomMediator $chatMediator) {\n        $this-\u003ename = $name;\n        $this-\u003echatMediator = $chatMediator;\n    }\n\n    public function getName() {\n        return $this-\u003ename;\n    }\n\n    public function send($message) {\n        $this-\u003echatMediator-\u003eshowMessage($this, $message);\n    }\n}\n```\nAnd the usage\n```php\n$mediator = new ChatRoom();\n\n$john = new User('John Doe', $mediator);\n$jane = new User('Jane Doe', $mediator);\n\n$john-\u003esend('Hi there!');\n$jane-\u003esend('Hey!');\n\n// Output will be\n// Feb 14, 10:58 [John]: Hi there!\n// Feb 14, 10:58 [Jane]: Hey!\n```\n\n💾 Memento\n-------\nReal world example\n\u003e Take the example of calculator (i.e. originator), where whenever you perform some calculation the last calculation is saved in memory (i.e. memento) so that you can get back to it and maybe get it restored using some action buttons (i.e. caretaker).\n\nIn plain words\n\u003e Memento pattern is about capturing and storing the current state of an object in a manner that it can be restored later on in a smooth manner.\n\nWikipedia says\n\u003e The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback).\n\nUsually useful when you need to provide some sort of undo functionality.\n\n**Programmatic Example**\n\nLets take an example of text editor which keeps saving the state from time to time and that you can restore if you want.\n\nFirst of all we have our memento object that will be able to hold the editor state\n\n```php\nclass EditorMemento\n{\n    protected $content;\n\n    public function __construct(string $content)\n    {\n        $this-\u003econtent = $content;\n    }\n\n    public function getContent()\n    {\n        return $this-\u003econtent;\n    }\n}\n```\n\nThen we have our editor i.e. originator that is going to use memento object\n\n```php\nclass Editor\n{\n    protected $content = '';\n\n    public function type(string $words)\n    {\n        $this-\u003econtent = $this-\u003econtent . ' ' . $words;\n    }\n\n    public function getContent()\n    {\n        return $this-\u003econtent;\n    }\n\n    public function save()\n    {\n        return new EditorMemento($this-\u003econtent);\n    }\n\n    public function restore(EditorMemento $memento)\n    {\n        $this-\u003econtent = $memento-\u003egetContent();\n    }\n}\n```\n\nAnd then it can be used as\n\n```php\n$editor = new Editor();\n\n// Type some stuff\n$editor-\u003etype('This is the first sentence.');\n$editor-\u003etype('This is second.');\n\n// Save the state to restore to : This is the first sentence. This is second.\n$saved = $editor-\u003esave();\n\n// Type some more\n$editor-\u003etype('And this is third.');\n\n// Output: Content before Saving\necho $editor-\u003egetContent(); // This is the first sentence. This is second. And this is third.\n\n// Restoring to last saved state\n$editor-\u003erestore($saved);\n\n$editor-\u003egetContent(); // This is the first sentence. This is second.\n```\n\n😎 Observer\n--------\nReal world example\n\u003e A good example would be the job seekers where they subscribe to some job posting site and they are notified whenever there is a matching job opportunity.   \n\nIn plain words\n\u003e Defines a dependency between objects so that whenever an object changes its state, all its dependents are notified.\n\nWikipedia says\n\u003e The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.\n\n**Programmatic example**\n\nTranslating our example from above. First of all we have job seekers that need to be notified for a job posting\n```php\nclass JobPost\n{\n    protected $title;\n\n    public function __construct(string $title)\n    {\n        $this-\u003etitle = $title;\n    }\n\n    public function getTitle()\n    {\n        return $this-\u003etitle;\n    }\n}\n\nclass JobSeeker implements Observer\n{\n    protected $name;\n\n    public function __construct(string $name)\n    {\n        $this-\u003ename = $name;\n    }\n\n    public function onJobPosted(JobPost $job)\n    {\n        // Do something with the job posting\n        echo 'Hi ' . $this-\u003ename . '! New job posted: '. $job-\u003egetTitle();\n    }\n}\n```\nThen we have our job postings to which the job seekers will subscribe\n```php\nclass EmploymentAgency implements Observable\n{\n    protected $observers = [];\n\n    protected function notify(JobPost $jobPosting)\n    {\n        foreach ($this-\u003eobservers as $observer) {\n            $observer-\u003eonJobPosted($jobPosting);\n        }\n    }\n\n    public function attach(Observer $observer)\n    {\n        $this-\u003eobservers[] = $observer;\n    }\n\n    public function addJob(JobPost $jobPosting)\n    {\n        $this-\u003enotify($jobPosting);\n    }\n}\n```\nThen it can be used as\n```php\n// Create subscribers\n$johnDoe = new JobSeeker('John Doe');\n$janeDoe = new JobSeeker('Jane Doe');\n\n// Create publisher and attach subscribers\n$jobPostings = new EmploymentAgency();\n$jobPostings-\u003eattach($johnDoe);\n$jobPostings-\u003eattach($janeDoe);\n\n// Add a new job and see if subscribers get notified\n$jobPostings-\u003eaddJob(new JobPost('Software Engineer'));\n\n// Output\n// Hi John Doe! New job posted: Software Engineer\n// Hi Jane Doe! New job posted: Software Engineer\n```\n\n🏃 Visitor\n-------\nReal world example\n\u003e Consider someone visiting Dubai. They just need a way (i.e. visa) to enter Dubai. After arrival, they can come and visit any place in Dubai on their own without having to ask for permission or to do some leg work in order to visit any place here; just let them know of a place and they can visit it. Visitor pattern lets you do just that, it helps you add places to visit so that they can visit as much as they can without having to do any legwork.\n\nIn plain words\n\u003e Visitor pattern lets you add further operations to objects without having to modify them.\n\nWikipedia says\n\u003e In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures. It is one way to follow the open/closed principle.\n\n**Programmatic example**\n\nLet's take an example of a zoo simulation where we have several different kinds of animals and we have to make them Sound. Let's translate this using visitor pattern\n\n```php\n// Visitee\ninterface Animal\n{\n    public function accept(AnimalOperation $operation);\n}\n\n// Visitor\ninterface AnimalOperation\n{\n    public function visitMonkey(Monkey $monkey);\n    public function visitLion(Lion $lion);\n    public function visitDolphin(Dolphin $dolphin);\n}\n```\nThen we have our implementations for the animals\n```php\nclass Monkey implements Animal\n{\n    public function shout()\n    {\n        echo 'Ooh oo aa aa!';\n    }\n\n    public function accept(AnimalOperation $operation)\n    {\n        $operation-\u003evisitMonkey($this);\n    }\n}\n\nclass Lion implements Animal\n{\n    public function roar()\n    {\n        echo 'Roaaar!';\n    }\n\n    public function accept(AnimalOperation $operation)\n    {\n        $operation-\u003evisitLion($this);\n    }\n}\n\nclass Dolphin implements Animal\n{\n    public function speak()\n    {\n        echo 'Tuut tuttu tuutt!';\n    }\n\n    public function accept(AnimalOperation $operation)\n    {\n        $operation-\u003evisitDolphin($this);\n    }\n}\n```\nLet's implement our visitor\n```php\nclass Speak implements AnimalOperation\n{\n    public function visitMonkey(Monkey $monkey)\n    {\n        $monkey-\u003eshout();\n    }\n\n    public function visitLion(Lion $lion)\n    {\n        $lion-\u003eroar();\n    }\n\n    public function visitDolphin(Dolphin $dolphin)\n    {\n        $dolphin-\u003espeak();\n    }\n}\n```\n\nAnd then it can be used as\n```php\n$monkey = new Monkey();\n$lion = new Lion();\n$dolphin = new Dolphin();\n\n$speak = new Speak();\n\n$monkey-\u003eaccept($speak);    // Ooh oo aa aa!    \n$lion-\u003eaccept($speak);      // Roaaar!\n$dolphin-\u003eaccept($speak);   // Tuut tutt tuutt!\n```\nWe could have done this simply by having an inheritance hierarchy for the animals but then we would have to modify the animals whenever we would have to add new actions to animals. But now we will not have to change them. For example, let's say we are asked to add the jump behavior to the animals, we can simply add that by creating a new visitor i.e.\n\n```php\nclass Jump implements AnimalOperation\n{\n    public function visitMonkey(Monkey $monkey)\n    {\n        echo 'Jumped 20 feet high! on to the tree!';\n    }\n\n    public function visitLion(Lion $lion)\n    {\n        echo 'Jumped 7 feet! Back on the ground!';\n    }\n\n    public function visitDolphin(Dolphin $dolphin)\n    {\n        echo 'Walked on water a little and disappeared';\n    }\n}\n```\nAnd for the usage\n```php\n$jump = new Jump();\n\n$monkey-\u003eaccept($speak);   // Ooh oo aa aa!\n$monkey-\u003eaccept($jump);    // Jumped 20 feet high! on to the tree!\n\n$lion-\u003eaccept($speak);     // Roaaar!\n$lion-\u003eaccept($jump);      // Jumped 7 feet! Back on the ground!\n\n$dolphin-\u003eaccept($speak);  // Tuut tutt tuutt!\n$dolphin-\u003eaccept($jump);   // Walked on water a little and disappeared\n```\n\n💡 Strategy\n--------\n\nReal world example\n\u003e Consider the example of sorting, we implemented bubble sort but the data started to grow and bubble sort started getting very slow. In order to tackle this we implemented Quick sort. But now although the quick sort algorithm was doing better for large datasets, it was very slow for smaller datasets. In order to handle this we implemented a strategy where for small datasets, bubble sort will be used and for larger, quick sort.\n\nIn plain words\n\u003e Strategy pattern allows you to switch the algorithm or strategy based upon the situation.\n\nWikipedia says\n\u003e In computer programming, the strategy pattern (also known as the policy pattern) is a behavioural software design pattern that enables an algorithm's behavior to be selected at runtime.\n\n**Programmatic example**\n\nTranslating our example from above. First of all we have our strategy interface and different strategy implementations\n\n```php\ninterface SortStrategy\n{\n    public function sort(array $dataset): array;\n}\n\nclass BubbleSortStrategy implements SortStrategy\n{\n    public function sort(array $dataset): array\n    {\n        echo \"Sorting using bubble sort\";\n\n        // Do sorting\n        return $dataset;\n    }\n}\n\nclass QuickSortStrategy implements SortStrategy\n{\n    public function sort(array $dataset): array\n    {\n        echo \"Sorting using quick sort\";\n\n        // Do sorting\n        return $dataset;\n    }\n}\n```\n\nAnd then we have our client that is going to use any strategy\n```php\nclass Sorter\n{\n    protected $sorterSmall;\n    protected $sorterBig;\n\n    public function __construct(SortStrategy $sorterSmall, SortStrategy $sorterBig)\n    {\n        $this-\u003esorterSmall = $sorterSmall;\n        $this-\u003esorterBig = $sorterBig;\n    }\n\n    public function sort(array $dataset): array\n    {\n        if (count($dataset) \u003e 5) {\n            return $this-\u003esorterBig-\u003esort($dataset);\n        } else {\n            return $this-\u003esorterSmall-\u003esort($dataset);\n        }\n    }\n}\n```\nAnd it can be used as\n```php\n$smalldataset = [1, 3, 4, 2];\n$bigdataset = [1, 4, 3, 2, 8, 10, 5, 6, 9, 7];\n\n$sorter = new Sorter(new BubbleSortStrategy(), new QuickSortStrategy());\n\n$sorter-\u003esort($dataset); // Output : Sorting using bubble sort\n\n$sorter-\u003esort($bigdataset); // Output : Sorting using quick sort\n```\n\n💢 State\n-----\nReal world example\n\u003e Imagine you are using some drawing application, you choose the paint brush to draw. Now the brush changes its behavior based on the selected color i.e. if you have chosen red color it will draw in red, if blue then it will be in blue etc.  \n\nIn plain words\n\u003e It lets you change the behavior of a class when the state changes.\n\nWikipedia says\n\u003e The state pattern is a behavioral software design pattern that implements a state machine in an object-oriented way. With the state pattern, a state machine is implemented by implementing each individual state as a derived class of the state pattern interface, and implementing state transitions by invoking methods defined by the pattern's superclass.\n\u003e The state pattern can be interpreted as a strategy pattern which is able to switch the current strategy through invocations of methods defined in the pattern's interface.\n\n**Programmatic example**\n\nLet's take an example of a phone. First of all we have our state interface and some state implementations\n\n```php\ninterface PhoneState {\n    public function pickUp(): PhoneState;\n    public function hangUp(): PhoneState;\n    public function dial(): PhoneState;\n}\n\n// states implementation\nclass PhoneStateIdle implements PhoneState {\n    public function pickUp(): PhoneState {\n        return new PhoneStatePickedUp();\n    }\n    public function hangUp(): PhoneState {\n        throw new Exception(\"already idle\");\n    }\n    public function dial(): PhoneState {\n        throw new Exception(\"unable to dial in idle state\");\n    }\n}\n\nclass PhoneStatePickedUp implements PhoneState {\n    public function pickUp(): PhoneState {\n        throw new Exception(\"already picked up\");\n    }\n    public function hangUp(): PhoneState {\n        return new PhoneStateIdle();\n    }\n    public function dial(): PhoneState {\n        return new PhoneStateCalling();\n    }\n}\n\nclass PhoneStateCalling implements PhoneState {\n    public function pickUp(): PhoneState {\n        throw new Exception(\"already picked up\");\n    }\n    public function hangUp(): PhoneState {\n        return new PhoneStateIdle();\n    }\n    public function dial(): PhoneState {\n        throw new Exception(\"already dialing\");\n    }\n}\n```\n\nThen we have our Phone class that changes the state on different behavior calls\n\n```php\nclass Phone {\n    private $state;\n\n    public function __construct() {\n        $this-\u003estate = new PhoneStateIdle();\n    }\n    public function pickUp() {\n        $this-\u003estate = $this-\u003estate-\u003epickUp();\n    }\n    public function hangUp() {\n        $this-\u003estate = $this-\u003estate-\u003ehangUp();\n    }\n    public function dial() {\n        $this-\u003estate = $this-\u003estate-\u003edial();\n    }\n}\n```\n\nAnd then it can be used as follows and it will call the relevant state methods:\n\n```php\n$phone = new Phone();\n\n$phone-\u003epickUp();\n$phone-\u003edial();\n```\n\n📒 Template Method\n---------------\n\nReal world example\n\u003e Suppose we are getting some house built. The steps for building might look like\n\u003e - Prepare the base of house\n\u003e - Build the walls\n\u003e - Add roof\n\u003e - Add other floors\n\n\u003e The order of these steps could never be changed i.e. you can't build the roof before building the walls etc but each of the steps could be modified for example walls can be made of wood or polyester or stone.\n\nIn plain words\n\u003e Template method defines the skeleton of how a certain algorithm could be performed, but defers the implementation of those steps to the children classes.\n\nWikipedia says\n\u003e In software engineering, the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in an operation, deferring some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm's structure.\n\n**Programmatic Example**\n\nImagine we have a build tool that helps us test, lint, build, generate build reports (i.e. code coverage reports, linting report etc) and deploy our app on the test server.\n\nFirst of all we have our base class that specifies the skeleton for the build algorithm\n```php\nabstract class Builder\n{\n\n    // Template method\n    final public function build()\n    {\n        $this-\u003etest();\n        $this-\u003elint();\n        $this-\u003eassemble();\n        $this-\u003edeploy();\n    }\n\n    abstract public function test();\n    abstract public function lint();\n    abstract public function assemble();\n    abstract public function deploy();\n}\n```\n\nThen we can have our implementations\n\n```php\nclass AndroidBuilder extends Builder\n{\n    public function test()\n    {\n        echo 'Running android tests';\n    }\n\n    public function lint()\n    {\n        echo 'Linting the android code';\n    }\n\n    public function assemble()\n    {\n        echo 'Assembling the android build';\n    }\n\n    public function deploy()\n    {\n        echo 'Deploying android build to server';\n    }\n}\n\nclass IosBuilder extends Builder\n{\n    public function test()\n    {\n        echo 'Running ios tests';\n    }\n\n    public function lint()\n    {\n        echo 'Linting the ios code';\n    }\n\n    public function assemble()\n    {\n        echo 'Assembling the ios build';\n    }\n\n    public function deploy()\n    {\n        echo 'Deploying ios build to server';\n    }\n}\n```\nAnd then it can be used as\n\n```php\n$androidBuilder = new AndroidBuilder();\n$androidBuilder-\u003ebuild();\n\n// Output:\n// Running android tests\n// Linting the android code\n// Assembling the android build\n// Deploying android build to server\n\n$iosBuilder = new IosBuilder();\n$iosBuilder-\u003ebuild();\n\n// Output:\n// Running ios tests\n// Linting the ios code\n// Assembling the ios build\n// Deploying ios build to server\n```\n\n## 🚦 Wrap Up Folks\n\nAnd that about wraps it up. I will continue to improve this, so you might want to watch/star this repository to revisit. Also, I have plans on writing the same about the architectural patterns, stay tuned for it.\n\n## 👬 Contribution\n\n- Report issues\n- Open pull request with improvements\n- Spread the word\n- Reach out with any feedback [![Twitter URL](https://img.shields.io/twitter/url/https/twitter.com/kamrify.svg?style=social\u0026label=Follow%20%40kamrify)](https://twitter.com/kamrify)\n\n## License\n\n[![License: CC BY 4.0](https://img.shields.io/badge/License-CC%20BY%204.0-lightgrey.svg)](https://creativecommons.org/licenses/by/4.0/)\n","funding_links":["https://github.com/sponsors/kamranahmedse"],"categories":["Others","📦 Legacy \u0026 Inactive Projects"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnilbuild%2Fdesign-patterns-for-humans","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnilbuild%2Fdesign-patterns-for-humans","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnilbuild%2Fdesign-patterns-for-humans/lists"}