Mi az a tervezési minta?
A tervezési minták tervezési szintű megoldások az ismétlődő problémákra, amelyekkel mi szoftvermérnökök gyakran találkozunk. Ez nem kód - ismétlem,❌ KÓD . Ez olyan, mint egy leírás arról, hogyan lehet ezeket a problémákat kezelni és megoldást tervezni.
Ezeknek a mintáknak a használata jó gyakorlatnak tekinthető, mivel a megoldás kialakítása meglehetősen bevált, ami a végső kód jobb olvashatóságát eredményezi. A tervezési mintákat meglehetősen gyakran hozzák létre és használják az OOP nyelvek, például a Java, amelyekben az innentől kezdve a legtöbb példa meg lesz írva.
Tervezési minták típusai
Körülbelül 26 minta található jelenleg (alig hiszem, hogy mindet megcsinálom ...).
Ezeket a 26 típusokat 3 típusba sorolhatjuk:
1. Kreatív: Ezeket a mintákat az osztály példányosítására tervezték. Lehetnek akár osztályteremtő minták, akár tárgyalkotási minták.
2. Strukturális: Ezeket a mintákat az osztály szerkezetére és összetételére figyelemmel tervezzük. E minták többségének fő célja az érintett osztály (ok) funkcionalitásának növelése, anélkül, hogy összetétele nagyban megváltozna.
3. Viselkedés: Ezeket a mintákat attól függően tervezzük, hogy az egyik osztály hogyan kommunikál másokkal.
Ebben a bejegyzésben egy-egy alapvető tervezési mintát fogunk átnézni minden osztályozott típushoz.
1. típus: Kreatív - The Singleton Design Pattern
A Singleton Design Pattern egy olyan kreatív minta, amelynek célja, hogy egy osztálynak csak egy példányát hozza létre, és csak egy globális hozzáférési pontot biztosítson az adott objektumhoz. A Java egyik ilyen osztályának egyik leggyakrabban használt példája a Naptár, ahol nem hozhat létre példányt az osztályból. Saját getInstance()
módszert is használ a felhasználandó objektum megszerzéséhez.
A szingulett tervezési mintát használó osztály a következőket tartalmazza:

- Privát statikus változó, amely az osztály egyetlen példányát tartalmazza.
- Magánépítő, így sehol máshol nem példázható.
- Nyilvános statikus módszer az osztály egyetlen példányának visszaadására.
A szinglettervezés sokféle megvalósítási módot kínál. Ma át fogom nézni a megvalósításait;
1. Lelkes azonnali beavatkozás
2. Lusta Instantiation
3. Szálbiztos azonnali beavatkozás
Stréber
public class EagerSingleton { // create an instance of the class. private static EagerSingleton instance = new EagerSingleton(); // private constructor, so it cannot be instantiated outside this class. private EagerSingleton() { } // get the only instance of the object created. public static EagerSingleton getInstance() { return instance; } }
Ez a fajta példányosítás az osztálybetöltés során történik, mivel a változó példány példányosítása bármilyen módszeren kívül történik. Ez komoly hátrányt jelent, ha ezt az osztályt egyáltalán nem használja az ügyfélalkalmazás. A készenléti terv, ha ezt az osztályt nem használják, a Lusta Instantiation.
Lusta napok
Nincs sok különbség a fenti megvalósítástól. A fő különbségek az, hogy a statikus változót eredetileg nullának nyilvánítják, és csak akkor példányosítják a getInstance()
módszeren belül - és csak akkor, ha - a példányváltozó az ellenőrzés idején semmis marad.
public class LazySingleton { // initialize the instance as null. private static LazySingleton instance = null; // private constructor, so it cannot be instantiated outside this class. private LazySingleton() { } // check if the instance is null, and if so, create the object. public static LazySingleton getInstance() { if (instance == null) { instance = new LazySingleton(); } return instance; } }
Ez megoldja az egyik problémát, de még mindig létezik egy másik. Mi van, ha két különböző kliens egyszerre lép be a Singleton osztályba, pontosan ezredmásodpercig? Nos, ellenőrizni fogják, hogy a példány egyszerre semmis-e meg, és igaznak találják-e, és így két osztály-példányt hoznak létre a két kliens minden egyes kérésére. Ennek kijavítására a Thread Safe példányosítást kell megvalósítani.
(Menet) A biztonság kulcsfontosságú
A Java-ban a szinkronizált kulcsszót metódusokon vagy objektumokon használják a szálbiztonság megvalósításához, így egyszerre csak egy szál fér hozzá egy adott erőforráshoz. Az osztálypéldány egy szinkronizált blokkba kerül, így a módszert csak egy kliens érheti el adott időben.
public class ThreadSafeSingleton { // initialize the instance as null. private static ThreadSafeSingleton instance = null; // private constructor, so it cannot be instantiated outside this class. private ThreadSafeSingleton() { } // check if the instance is null, within a synchronized block. If so, create the object public static ThreadSafeSingleton getInstance() { synchronized (ThreadSafeSingleton.class) { if (instance == null) { instance = new ThreadSafeSingleton(); } } return instance; } }
A szinkronizált módszer költsége magas, és csökkenti az egész művelet teljesítményét.
Például, ha a példányváltozót már példányosították, akkor minden alkalommal, amikor bármelyik ügyfél hozzáfér a getInstance()
metódushoz, a synchronized
módszer futtatásra kerül, és a teljesítmény csökken. Ez csak azért történik, hogy ellenőrizzük, hogy a instance
változók értéke nulla-e. Ha úgy találja, hogy az, akkor elhagyja a módszert.
A rezsicsökkentés érdekében kettős reteszt használnak. Az ellenőrzést a synchronized
metódus előtt is használják , és ha az érték önmagában nulla, akkor synchronized
fut a módszer.
// double locking is used to reduce the overhead of the synchronized method public static ThreadSafeSingleton getInstanceDoubleLocking() { if (instance == null) { synchronized (ThreadSafeSingleton.class) { if (instance == null) { instance = new ThreadSafeSingleton(); } } } return instance; }
Most a következő osztályozásra.
2. típus: Szerkezeti - A dekoratőr mintája
Adok neked egy kis forgatókönyvet, hogy jobb kontextust kapjak arról, hogy miért és hol érdemes használni a Dekoratőr mintát.
Tegyük fel, hogy Önnek van egy kávézója, és mint minden újoncnak, csak kétféle sima kávéval kezdheti, a ház keverékével és a sötét pörköléssel. Számlázási rendszerében egy osztály volt a különböző kávékeverékekre, amely az ital absztrakt osztályt örökli. Az emberek valójában kezdenek jönni, és megeszik a csodálatos (bár keserű?) Kávédat. Aztán vannak a kávé újdonságai, amelyek, ne adj Isten, cukrot vagy tejet akarnak. Ilyen travesty kávéra !! ??
Most meg kell, hogy legyen ez a két kiegészítő is, mind a menüben, mind pedig sajnos a számlázási rendszerben. Eredetileg informatikusa mindkét kávé számára alkategóriát készít, az egyik cukrot, a másik tejet tartalmaz. Aztán, mivel az ügyfeleknek mindig igazuk van, az ember ezeket a rettegett szavakat mondja:
- Kérhetnék egy tejeskávét cukorral?
???
A számlázási rendszer megint az arcodba nevet. Nos, térjünk vissza a rajztáblára ...
The IT person then adds milk coffee with sugar as another subclass to each parent coffee class. The rest of the month is smooth sailing, people lining up to have your coffee, you actually making money. ??
But wait, there’s more!
The world is against you once again. A competitor opens up across the street, with not just 4 types of coffee, but more than 10 add-ons as well! ?
You buy all those and more, to sell better coffee yourself, and just then remember that you forgot to update that dratted billing system. You quite possibly cannot make the infinite number of subclasses for any and all combinations of all the add-ons, with the new coffee blends too. Not to mention, the size of the final system.??
Time to actually invest in a proper billing system. You find new IT personnel, who actually knows what they are doing and they say;
“Why, this will be so much easier and smaller if it used the decorator pattern.”
What on earth is that?
The decorator design pattern falls into the structural category, that deals with the actual structure of a class, whether is by inheritance, composition or both. The goal of this design is to modify an objects’ functionality at runtime. This is one of the many other design patterns that utilize abstract classes and interfaces with composition to get its desired result.
Let’s give Math a chance (shudder?) to bring this all into perspective;
Take 4 coffee blends and 10 add-ons. If we stuck to the generation of subclasses for each different combination of all the add-ons for one type of coffee. That’s;
(10–1)² = 9² = 81 subclasses
We subtract 1 from the 10, as you cannot combine one add-on with another of the same type, sugar with sugar sounds stupid. And that’s for just one coffee blend. Multiply that 81 by 4 and you get a whopping 324 different subclasses! Talk about all that coding…
But with the decorator pattern will require only 16 classes in this scenario. Wanna bet?


If we map out our scenario according to the class diagram above, we get 4 classes for the 4 coffee blends, 10 for each add-on and 1 for the abstract component and 1 more for the abstract decorator. See! 16! Now hand over that $100.?? (jk, but it will not be refused if given… just saying)
As you can see from above, just as the concrete coffee blends are subclasses of the beverage abstract class, the AddOn abstract class also inherits its methods from it. The add-ons, that are its subclasses, in turn inherit any new methods to add functionality to the base object when needed.
Let’s get to coding, to see this pattern in use.
First to make the Abstract beverage class, that all the different coffee blends will inherit from:
public abstract class Beverage { private String description; public Beverage(String description) { super(); this.description = description; } public String getDescription() { return description; } public abstract double cost(); }
Then to add both the concrete coffee blend classes.
public class HouseBlend extends Beverage { public HouseBlend() { super(“House blend”); } @Override public double cost() { return 250; } } public class DarkRoast extends Beverage { public DarkRoast() { super(“Dark roast”); } @Override public double cost() { return 300; } }
The AddOn abstract class also inherits from the Beverage abstract class (more on this below).
public abstract class AddOn extends Beverage { protected Beverage beverage; public AddOn(String description, Beverage bev) { super(description); this.beverage = bev; } public abstract String getDescription(); }
And now the concrete implementations of this abstract class:
public class Sugar extends AddOn { public Sugar(Beverage bev) { super(“Sugar”, bev); } @Override public String getDescription() { return beverage.getDescription() + “ with Mocha”; } @Override public double cost() { return beverage.cost() + 50; } } public class Milk extends AddOn { public Milk(Beverage bev) { super(“Milk”, bev); } @Override public String getDescription() { return beverage.getDescription() + “ with Milk”; } @Override public double cost() { return beverage.cost() + 100; } }
As you can see above, we can pass any subclass of Beverage to any subclass of AddOn, and get the added cost as well as the updated description. And, since the AddOn class is essentially of type Beverage, we can pass an AddOn into another AddOn. This way, we can add any number of add-ons to a specific coffee blend.
Now to write some code to test this out.
public class CoffeeShop { public static void main(String[] args) { HouseBlend houseblend = new HouseBlend(); System.out.println(houseblend.getDescription() + “: “ + houseblend.cost()); Milk milkAddOn = new Milk(houseblend); System.out.println(milkAddOn.getDescription() + “: “ + milkAddOn.cost()); Sugar sugarAddOn = new Sugar(milkAddOn); System.out.println(sugarAddOn.getDescription() + “: “ + sugarAddOn.cost()); } }
The final result is:

It works! We were able to add more than one add-on to a coffee blend and successfully update its final cost and description, without the need to make infinite subclasses for each add-on combination for all coffee blends.
Finally, to the last category.
Type 3: Behavioral - The Command Design Pattern
A behavioral design pattern focuses on how classes and objects communicate with each other. The main focus of the command pattern is to inculcate a higher degree of loose coupling between involved parties (read: classes).
Uhhhh… What’s that?
Coupling is the way that two (or more) classes that interact with each other, well, interact. The ideal scenario when these classes interact is that they do not depend heavily on each other. That’s loose coupling. So, a better definition for loose coupling would be, classes that are interconnected, making the least use of each other.
The need for this pattern arose when requests needed to be sent without consciously knowing what you are asking for or who the receiver is.
In this pattern, the invoking class is decoupled from the class that actually performs an action. The invoker class only has the callable method execute, which runs the necessary command, when the client requests it.
Let’s take a basic real-world example, ordering a meal at a fancy restaurant. As the flow goes, you give your order (command) to the waiter (invoker), who then hands it over to the chef(receiver), so you can get food. Might sound simple… but a bit meh to code.

The idea is pretty simple, but the coding goes around the nose.

The flow of operation on the technical side is, you make a concrete command, which implements the Command interface, asking the receiver to complete an action, and send the command to the invoker. The invoker is the person that knows when to give this command. The chef is the only one who knows what to do when given the specific command/order. So, when the execute method of the invoker is run, it, in turn, causes the command objects’ execute method to run on the receiver, thus completing necessary actions.
What we need to implement is;
- An interface Command
- A class Order that implements Command interface
- A class Waiter (invoker)
- A class Chef (receiver)
So, the coding goes like this:
Chef, the receiver
public class Chef { public void cookPasta() { System.out.println(“Chef is cooking Chicken Alfredo…”); } public void bakeCake() { System.out.println(“Chef is baking Chocolate Fudge Cake…”); } }
Command, the interface
public interface Command { public abstract void execute(); }
Order, the concrete command
public class Order implements Command { private Chef chef; private String food; public Order(Chef chef, String food) { this.chef = chef; this.food = food; } @Override public void execute() { if (this.food.equals(“Pasta”)) { this.chef.cookPasta(); } else { this.chef.bakeCake(); } } }
Waiter, the invoker
public class Waiter { private Order order; public Waiter(Order ord) { this.order = ord; } public void execute() { this.order.execute(); } }
You, the client
public class Client { public static void main(String[] args) { Chef chef = new Chef(); Order order = new Order(chef, “Pasta”); Waiter waiter = new Waiter(order); waiter.execute(); order = new Order(chef, “Cake”); waiter = new Waiter(order); waiter.execute(); } }
As you can see above, the Client makes an Order and sets the Receiver as the Chef. The Order is sent to the Waiter, who will know when to execute the Order (i.e. when to give the chef the order to cook). When the invoker is executed, the Orders’ execute method is run on the receiver (i.e. the chef is given the command to either cook pasta ? or bake cake?).
Quick recap
In this post we went through:
- What a design pattern really is,
- The different types of design patterns and why they are different
- One basic or common design pattern for each type
I hope this was helpful.
Find the code repo for the post, here.