Software design patterns (2): factory, facade, mediator and decorator patterns

Preface

        In this article, Lizhi will sort out four software design patterns: factory pattern, facade pattern, mediator pattern and decorator pattern. The more important ones are the factory mode and the decorator mode. The factory mode is used more frequently in development. I hope this article by Lizhi can explain it clearly hahahaha, and I hope it can help friends in need~~~


Article directory

Preface

1. Factory model

1.1 Simple Factory

1.2 Factory method

1.3 Abstract Factory

2. Mediator mode and facade mode

2.1 Facade mode Facade

2.2 Mediator Mode Mediator

3. Decorator mode Decorator 

Summarize


1. Factory model

1.1 Simple Factory

First define a factory function interface Moveable for a vehicle.

package com.crj.factorymethod;
/**
 * 工厂函数接口
 */
public interface Moveable {
    void go();
}

 If we want to implement a certain mode of transportation, we need to implement the interface and override the go method by implementing the transportation class.

package com.crj.factorymethod;

/**
 * Car类继承工厂函数接口
 */
public class Car implements  Moveable {
    public void go() {
        System.out.println("Car go wuwuwuwuw....");
    }
}

Use the simple factory pattern to return the instantiated vehicle object.

package com.crj.factorymethod;

/**
 * 简单工厂模式
 * 简单工厂的可扩展性不好
 */
public class SimpleVehicleFactory {
    public Car createCar() {
        //before processing
        return new Car();
    }

    public Broom createBroom() {
        return new Broom();
    }
}

1.2 Factory method

        As can be seen from the above, the scalability of the simple factory pattern is relatively poor, but when we need to create a new mode of transportation, we need to redefine and hard-code the corresponding object methods in the factory SimpleVehicleFactory. This is not easy in the later stage. maintain. Then you can also have a factory for different means of transportation. The method types are all inherited from Moveable, and the return value is also of Moveable type.

package com.crj.factorymethod;

/**
 * 工厂方法
 */
public class CarFactory {
    public Moveable create() {
        System.out.println("a car created!");
        return new Car();
    }
}

main method

package com.crj.factorymethod;

public class Main {
    public static void main(String[] args) {
        Moveable m = new CarFactory().create();
        m.go();
    }
}

1.3 Abstract Factory

We have already mapped the product construction to the factory one-to-one, but it is not very convenient for us to operate the product cluster. We can directly create an entire product cluster through the abstract factory. Before creating product clusters, we need to create abstract product classes, abstract factories, concrete product classes and concrete factories.

abstract product class

First define some abstract product classes and define corresponding abstract methods.

AbstractFactoryAbstractFactory

An abstract factory defines abstract methods for creating products of the corresponding type in the product cluster. 

package com.mashibing.dp.abstractfactory;

public abstract class AbastractFactory {
    abstract Food createFood();
    abstract Vehicle createVehicle();
    abstract Weapon createWeapon();
}

Concrete factory class

The concrete factory class inherits from the abstract factory class and overrides the methods for creating products for different types of products. 

Specific product categories

Concrete product classes inherit from abstract product classes

main file

        In the main file, we obtain the object by instantiating the specific product class and call the corresponding product creation method to first create the product cluster. You can see that in this demo, even if we need to get different product clusters, we only need to instantiate different factory classes.

package com.mashibing.dp.abstractfactory;

public class Main {
    public static void main(String[] args) {
        AbastractFactory f = new ModernFactory();

        Vehicle c = f.createVehicle();
        c.go();
        Weapon w = f.createWeapon();
        w.shoot();
        Food b = f.createFood();
        b.printName();
    }
}

You can look at this picture for the specific logic. I feel like I still haven’t explained it very clearly. I have to rely on everyone’s cleverness for the remaining three points.


2. Mediator mode and facade mode

2.1 Facade mode Facade

        The facade pattern requires that communication between the outside and the inside of a system must be carried out through a unified object, and the communication between the external communication and the internal object cluster is managed through a high-level interface. A simple understanding is an intermediary (facade), and the outside only needs to communicate with this The intermediary can be connected, and the intermediary will delegate the request sent by the client to the corresponding subsystem. This is also a black box operation. In this mode, you can have one or more systems at the same time. Each system is a collection of classes, and the system only treats the facade as a client.

have to be aware of is:

  • A system can have multiple facades

  • The facade does not participate in the business logic within the system

2.2 Mediator Mode Mediator

        The mediator mode is equivalent to a star connection. This mode is mostly used in message middleware such as MQ. Objects only need to communicate with the middleman. The middleman sends, receives and processes messages, which is a decoupled operation. The details of the difference between facade mode and mediator mode can be seen in the figure below. In fact, the difference between the two is not big and they are interchangeable in some scenarios.


3. Decorator mode Decorator 

The definition of the Decorator pattern: It refers to a pattern that dynamically adds some functions to the object without changing the existing object structure. It belongs to the object structural pattern.

advantage:

  • Decorators are a powerful supplement to inheritance and are more flexible than inheritance. They can dynamically extend functions for an object without changing the original object, and are plug-and-play.
  • Different effects can be achieved by using different decorative classes and the arrangement and combination of these decorative classes.
  • The decorator pattern fully adheres to the opening and closing principle

Disadvantages: The decorator pattern will add many subclasses, and excessive use will increase program complexity.

After roughly looking at some conceptual things, Big Machine seems not to be particularly concrete. Below we can use an example to understand what kind of software design pattern the decorator pattern is. 

package com.crj.Decorator;

public class Decorator {
    /**
     * 装饰器模式
     * 使用实体装饰类装饰
     * @param args
     */
    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        RedShapeDecorator rda = new RedShapeDecorator(a);
        rda.draw();
        BlueShapeDecorator rdb = new BlueShapeDecorator(b);
        rdb.draw();
    }
}

/**
 * 接口
 */
interface Shape{
    void draw();
}

/**
 * 接口实现类
 */
class A implements Shape{
    @Override
    public void draw() {
        System.out.println("这是A类");
    }
}
class B implements  Shape{
    @Override
    public void draw() {
        System.out.println("这是B类");
    }
}

/**
 * 抽象装饰类
 */
abstract class ShapeDecorator implements Shape{
    protected Shape decoratedShape;

    public ShapeDecorator(Shape decoratedShape) {
        this.decoratedShape = decoratedShape;
    }

    @Override
    public void draw() {
        decoratedShape.draw();
    }
}

/**
 * 第一个实体装饰类
 */
class RedShapeDecorator extends ShapeDecorator{
    public RedShapeDecorator(Shape decoratedShape) {
        super(decoratedShape);
    }

    @Override
    public void draw() {
        super.draw();
        setRedShapeDecorator(decoratedShape);
    }
    private void setRedShapeDecorator(Shape decoratedShape){
        System.out.println("Red");
    }
}
/**
 * 第二个实体装饰类
 */
class BlueShapeDecorator extends ShapeDecorator{
    public BlueShapeDecorator(Shape decoratedShape) {
        super(decoratedShape);
    }
    @Override
    public void draw() {
        super.draw();
        setRedShapeDecorator(decoratedShape);
    }
    private void setRedShapeDecorator(Shape decoratedShape){
        System.out.println("Blue");
    }
}

        In the demo above, we defined a common interface, two basic interface implementation classes, an abstract decoration class and two entity decoration classes. Both interface implementation classes and abstract decoration classes implement the implementation methods of the interface and override the interface methods. The entity decoration class inherits from the abstract decoration class. Since the abstract decoration class contains a parameterized constructor, it is necessary to use the super keyword to declare the inherited object. We decorate the draw() method called on the object by passing an entity class object into the entity decoration class object.

        Looking at this picture, we can find that we actually define a ShapeDecorator abstract decoration class for decoration on the Shape interface. The so-called decoration is actually to add functionality. We also mentioned earlier that the essence of decoration is to use abstract classes to inherit interfaces, and then use specific implementation classes to decorate functions. This method excellently solves the problem of subclass explosion.


Summarize

        So far, Lizhi has sorted out several design patterns. Let me summarize my learning method: I mainly sorted it out based on the documentation and video resources of experts. I then implemented it by typing examples by myself. The gains and experience are indeed quite great. Learning design patterns may be boring. Come on everyone, Lizhi must keep moving forward~

Today has become the past, but we still look forward to the future tomorrow! I am Xiaolizhi, and I will accompany you on the road of technological growth. Coding is not easy, so please raise your little paw and give me a thumbs up, hahaha~~~ Bixinxin♥~~~

Guess you like

Origin blog.csdn.net/qq_62706049/article/details/132710160