Interview Essentials: Summary of Common Design Patterns

Design mode is the precipitation of programmers' best practices for many years in the design process, which can improve the quality of research and development and communication efficiency between engineers.


I used the template method mode in the X game access platform. Scenario: The developed game needs to be pushed to different channels. The user login and recharge interface implementation of each channel is different, and the X game platform is used as a game interface. Service platforms that enter different channels need to ensure the consistency of game access and eliminate the differences in different channels.
Benefits of using the template method:

  1. Fixed the process of game access: login, recharge access;
  2. Protocol and implementation are decoupled: each channel is accessed according to the corresponding docking protocol difference, and the difference is erased at the upper layer.
  3. Scalability is better; new channels can be added easily;
  4. Can handle game access more flexibly;

In the process of optimizing the login code, I used the observer mode. For example, you can use Spring's event mechanism or the EventBus provided by guava; the

previous login code is noodle style, and one line of code handles a corresponding logic. For example, after the login is completed, the log is recorded, the point service is notified to increase the points, and the statistics service is notified to increase the login. Number of times (using singleton mode), change the daily activity;

after using the viewer mode, send a login success message, and process different logical operations in the listener. The code is simplified, maintainability, and scalability are improved.

One: Singleton Mode Usage scenario: The counter of the website is generally implemented in a singleton mode, otherwise it is difficult to synchronize.


To put it simply, there is only one instance object of a certain class in an application. You can't go to new because the constructor is decorated by private. Generally, the instance of them is obtained through the getInstance() method. The return value of getInstance() is a reference to an object, not a new instance, so don't misunderstand it as multiple objects. The singleton mode is also very easy to implement, just look at the demo directly

public class Singleton {

    private static Singleton singleton;

    private Singleton() {
    }

    public static Singleton getInstance() {         if (singleton == null) {             singleton = new Singleton();         }         return singleton;     } } According to my habit, I can’t wait to write full comments. I’m afraid you won’t understand it, but this code is too It's simple, so I didn't write any comments. If you don't understand these few lines of code, then you can wash and sleep. When you wake up, look at my blog and maybe you can understand it.







Two: Observer mode 
has a one-to-many dependency relationship between objects. When the state of an object changes, all objects that depend on it are notified and automatically updated. Various Listeners in Android use this design pattern. As long as the user operates the phone, the corresponding listener will be notified and respond to the process. 


Give you a chestnut: Suppose there are three people, Xiaomei (female, 28), Lao Wang and Lao Li. Xiaomei is very beautiful and coquettish. Lao Wang and Lao Li are two middle-aged male dicks, always paying attention to her every move. One day, Xiaomei said: My husband is not at home today, it is so boring to be alone~~~ This sentence was heard by Lao Wang and Lao Li, and the result was broken, and she was very happy. After a while, Lao Wang I rushed to the door of Xiaomei’s house, so I walked in........................ Pa~Papa Papa Papa~ 
Here, Xiao Mei is the observer, and Lao Wang and Lao Li are the observers. The observer sends a message, and then the observer performs the corresponding processing, see the code:

public interface Person {     //Lao Wang and Lao Li can receive messages from Xiao Mei through this interface     void getMessage(String s); } This interface is equivalent to Lao Wang and Lao Li’s phone number, when Xiao Mei sends a notification Will call getMessage this call, the call is to call the interface, it doesn’t matter if you don’t understand, look down first




public class LaoWang implements Person {

    private String name = "老王";

    public LaoWang() {
    }

    @Override
    public void getMessage(String s) {         System.out.println(name + "Received a call from Xiaomei, the content of the call is: "+ s);     }

}

public class LaoLi implements Person {

    private String name = "老李";

    public LaoLi() {     }

    @Override
    public void getMessage(String s) {         System.out.println(name + "Received a call from Xiaomei, the content of the call is: ->" + s);     }

}The

code is very simple, let’s take a look at Xiaomei’s code:

public class XiaoMei {
    List<Person> list = new ArrayList<Person>();
     public XiaoMei(){
     }

     public void addPerson(Person person){
         list.add(person);
     }

     // Traverse the list and send your notifications to everyone who has a crush on you
     public void notifyPerson() {          for(Person person:list){              person.getMessage("I’m alone at home today, come here, whoever comes first You can get me!");          }      } } Let’s write a test class to see if the result is correct





public class Test {
    public static void main(String[] args) {

        XiaoMei xiao_mei = new XiaoMei();
        LaoWang lao_wang = new LaoWang();
        LaoLi lao_li = new LaoLi();

        //Lao Wang and Lao Li both registered with
        Xiaomei xiao_mei.addPerson(lao_wang);
        xiao_mei.addPerson(lao_li);

        //Xiaomei sends notifications to Lao Wang and Lao Li
        xiao_mei.notifyPerson();
    }
}

I took a screenshot of the running result and it was 
 
perfect~~~

Three: The decorator mode 
further encapsulates the existing business logic to add additional functions. For example, the decorator mode is used in the IO stream in java. When the user uses it, he can assemble it at will to achieve what he wants effect. 


Give a chestnut, I want to eat a sandwich. First of all I need a big sausage. I like to eat cream. Put a little cream on the sausage, put a little vegetable, and finally add two slices of bread. A very hearty lunch. , Nutrition and health, then how should we write code? 
First, we need to write a Food class so that all other foods inherit this class. Look at the code:

public class Food {

    private String food_name;

    public Food() {
    }

    public Food(String food_name) {
        this.food_name = food_name;
    }

    public String make() {         return food_name;     }; } The code is very simple, I will not explain it, and then we write a few subclasses to inherit it:




//Bread class
public class Bread extends Food {

    private Food basic_food;

    public Bread(Food basic_food) {
        this.basic_food = basic_food;
    }

    public String make() {
        return basic_food.make()+"+面包";
    }
}

//Cream class
public class Cream extends Food {

    private Food basic_food;

    public Cream(Food basic_food) {
        this.basic_food = basic_food;
    }

    public String make() {
        return basic_food.make()+"+奶油";
    }
}

//Vegetable
public class Vegetable extends Food {

    private Food basic_food;

    public Vegetable(Food basic_food) {
        this.basic_food = basic_food;
    }

    public String make() {
        return basic_food.make()+"+蔬菜";
    }

}

These classes are similar. The construction method passes in a Food type parameter, and then adds some of your own logic to the make method. If you still don’t understand why you write it, don’t worry, you can take a look at my Test How to write the class, you will understand at a glance

public class Test {     public static void main(String[] args) {         Food food = new Bread(new Vegetable(new Cream(new Food("Sausage"))));         System.out.println(food.make()) ;     } } See no, layer by layer encapsulation, I did not look from the inside out: at the innermost I have a new sausage, on the outside of the sausage I wrapped a layer of cream, and on the outside of the cream I added a layer of vegetables , I put bread on the outside. Isn’t it very vivid? Haha. This design pattern is exactly the same as in real life. Do you understand it? Let's take a look at the results of the operation.  A sandwich is ready~~~







 

Four: The adapter mode 
connects two completely different things together, just like a transformer in real life.

Suppose a mobile phone charger needs a voltage of 20V, but the normal voltage is 220V. At this time, a transformer is needed to convert the 220V voltage to a 20V voltage. In this way, the transformer connects the 20V voltage to the mobile phone.

public class Test {
    public static void main(String[] args) {
        Phone phone = new Phone();
        VoltageAdapter adapter = new VoltageAdapter();
        phone.setAdapter(adapter);
        phone.charge();
    }
}

// mobile phone
class Phone {

    public static final int V = 220;// The normal voltage is 220v, which is a constant

    private VoltageAdapter adapter;

    // 充电
    public void charge() {
        adapter.changeVoltage();
    }

    public void setAdapter(VoltageAdapter adapter) {
        this.adapter = adapter;
    }
}

// Transformer
class VoltageAdapter {     // Function to change voltage     public void changeVoltage() {         System.out.println("Charging...");         System.out.println("Original voltage:" + Phone.V + " V");         System.out.println("Voltage after transformer conversion:" + (Phone.V-200) + "V");     } }







 


Five: Factory mode. 
Simple factory mode: an abstract interface, multiple implementation classes of abstract interfaces, and a factory class to instantiate abstract interfaces

// Abstract product class
abstract class Car {     public void run();

    public void stop();
}

// Specific implementation class
class Benz implements Car {     public void run() {         System.out.println("Benz started to start...");     }


    public void stop() {         System.out.println("Benz has stopped...");     } }


class Ford implements Car {     public void run() {         System.out.println("Ford started...");     }


    public void stop() {         System.out.println("Ford stopped...");     } }


// 工厂类
class Factory {
    public static Car getCarInstance(String type) {
        Car c = null;
        if ("Benz".equals(type)) {
            c = new Benz();
        }
        if ("Ford".equals(type)) {
            c = new Ford();
        }
        return c;
    }
}

public class Test {

    public static void main(String[] args) {         Car c = Factory.getCarInstance("Benz");         if (c != null) {             c.run();             c.stop();         } else {             System.out. println("Can't make this kind of car...");         }






    }

}

Factory method pattern: There are four roles, abstract factory pattern, concrete factory pattern, abstract product pattern, and concrete product pattern. It is no longer a factory class to instantiate a concrete product, but a subclass of the abstract factory to instantiate the product

// Abstract product role
public interface Moveable {     void run(); }

// 具体产品角色
public class Plane implements Moveable {
    @Override
    public void run() {
        System.out.println("plane....");
    }
}

public class Broom implements Moveable {
    @Override
    public void run() {
        System.out.println("broom.....");
    }
}

// abstract factory
public abstract class VehicleFactory {     abstract Moveable create(); }

// 具体工厂
public class PlaneFactory extends VehicleFactory {
    public Moveable create() {
        return new Plane();
    }
}

public class BroomFactory extends VehicleFactory {
    public Moveable create() {
        return new Broom();
    }
}

// Test class
public class Test {     public static void main(String[] args) {         VehicleFactory factory = new BroomFactory();         Moveable m = factory.create();         m.run();     } } Abstract factory pattern: and factory The difference between the method pattern is that the factory in the factory method pattern only produces a single product, while the factory in the abstract factory pattern produces multiple products







/抽象工厂类
public abstract class AbstractFactory {
    public abstract Vehicle createVehicle();
    public abstract Weapon createWeapon();
    public abstract Food createFood();
}
//具体工厂类,其中Food,Vehicle,Weapon是抽象类,
public class DefaultFactory extends AbstractFactory{
    @Override
    public Food createFood() {
        return new Apple();
    }
    @Override
    public Vehicle createVehicle() {
        return new Car();
    }
    @Override
    public Weapon createWeapon() {
        return new AK47();
    }
}
//测试类
public class Test {
    public static void main(String[] args) {
        AbstractFactory f = new DefaultFactory();
        Vehicle v = f.createVehicle();
        v.run();
        Weapon w = f.createWeapon();
        w.shoot();
        Food a = f.createFood();
        a.printName();
    }
}

Six: What is the template method pattern?

Answer: The template method pattern refers to defining a template structure and deferring the specific content to the subclass for implementation.

Advantages :

  • Improve code reusability: put the same part of the code in an abstract parent class, and put different codes in different subclasses;
  • Reverse control is realized: the operation of calling its subclasses by a parent class, and the expansion of different behaviors through the specific realization of subclasses, realizes reverse control and conforms to the principle of opening and closing.

Take the example of putting fruits in the refrigerator. For example, I want to put a banana: open the refrigerator door → put the banana → close the refrigerator door; if I want to put another apple: open the refrigerator door → put the apple → close the refrigerator door. It can be seen that the behavior patterns between them are the same, except that the stored fruit categories are different. At this time, the template method pattern is very suitable to solve this problem. The implementation code is as follows:

/\* \* 添加模板方法 \*/
abstract class Refrigerator {
    public void open() {
        System.out.println("开冰箱门");
    }
    public abstract void put();

    public void close() {
        System.out.println("关冰箱门");
    }
}
class Banana extends Refrigerator {
    @Override
    public void put() {
        System.out.println("放香蕉");
    }
}
class Apple extends Refrigerator {
    @Override
    public void put() {
        System.out.println("放苹果");
    }
}
/\* \* 调用模板方法 \*/
public class TemplateTest {
    public static void main(String[] args) {
        Refrigerator refrigerator = new Banana();
        refrigerator.open();
        refrigerator.put();
        refrigerator.close();
    }
}

Program execution result:

Open the refrigerator door

Put bananas

Close the refrigerator door

Guess you like

Origin blog.csdn.net/zhangleiyes123/article/details/108182097