Xiaodi classroom - learning notes: do you know structural design mode, decorator + agent mode? Stay and talk

Vision: "make programming no longer difficult to learn and make technology and life more interesting"

For more architecture courses, please visit xdclass net

 

catalogue

Episode 1 design mode of adding wings to the tiger - Introduction to decorator design mode

Episode 2 meet Lao Wang's refitting collocation - play with the design mode of decorator

Episode 3 Stream IO stream in JDK source code - Application of decorator design pattern

Episode 4 here comes the franchisee - the agent design mode you need to master

Episode 5 here comes the franchisee - the agent design mode you need to master

6 - how many third-party designs do you know about them?

Episode 7 case practice - Application of appearance design mode in multi-channel message push

Episode 8 how much do you know about Flyweight Pattern

Episode 9 Lao Wang's website outsourcing - Xiangyuan design mode case practice, advantages and disadvantages

Dry goods document

Introduction: Explanation - introduction of decorator design mode and application scenario

  • Decorator Pattern

    • Also known as packaging design pattern, it belongs to structural pattern. It is a package of existing classes, which allows adding new functions to an existing object without changing its structure
    • To add functions to objects, there are generally two ways of inheritance or association combination. The object of one class is embedded in another object, and the other object determines whether to call the behavior of the embedded object to enhance functions. This is the decorator mode, which is more flexible than the inheritance mode

 

  • Application scenario

    • Xiaodi classroom - Lao Wang originally planned to buy a sports car to flirt with his sister. As a result, he had no money in his pocket and bought a bicycle instead. In order to be prominent, the store provided a variety of modification schemes, including a large horn and an explosion-proof tire. After decoration, he became a bicycle with a clearer purpose and can better solve the problem. The pattern of constantly adding decoration to objects is called Decorator pattern, which refers to ornaments.

    • Add responsibilities to a single object in a dynamic and transparent manner without changing its structure

    • The most widely used in JDK source code is IO stream, which uses a lot of decoration design patterns

       

  • Role (decorator and decoratee have the same superclass (Component))

    • Abstract Component

      • Define the specification of decoration method. The original bicycle only defines the API of bicycle;

       

    • Decorated (ConcreteComponent)

      • The specific implementation of Component, that is, the specific object we want to decorate
      • Realize the specific role of the core role

       

    • Decorator component

      • Define the behavior specification of the specific decorator, have the same interface with the Component role, and hold the instance reference of the Component object

      • Bicycle components have names and prices

         

       

    • Concrete decorator

      • Be responsible for decorating additional functions for component objects
      • Such as horn, explosion-proof tire

 

 

 

 

 

 

 

 

 

 

 

Episode 2 meet Lao Wang's refitting collocation - play with the design mode of decorator

Introduction: decoration design mode case practice

  • Background needs


Droplet classroom-Lao Wang, because the company has issued a project bonus, if it is not enough to buy sports cars, it will buy Bicycles first. There are small, medium and large bicycles in the store.
​
Then one horn was added in the transformation. Later, one more horn was added if it was not enough. One explosion-proof tire was not enough, and there were two. There were many random combinations of modifications. 
​
The shopkeepers are distressed. Such a structure is difficult to do, and the price is difficult to calculate. Moreover, if the demand changes again, it will be even more troublesome.
​
Using decorators can solve this problem

  • What would you do without using design patterns? Try it yourself and see if it's flexible enough

 

  • Coding practice with decorator design mode

 

 

  • advantage

    • The purpose of decoration pattern and inheritance relationship is to extend the function of objects, but decoration pattern can provide more flexibility than inheritance.
    • Using different specific decorative classes and the arrangement and combination of these decorative classes can create many combinations of different behaviors. The original code does not need to be changed and conforms to the "opening and closing principle"
  • shortcoming

    • Decoration mode adds many subclasses, which will make the program very complex (multi-layer packaging) if overused
    • Increase the complexity of the system and increase the difficulty of learning and understanding

 

  • Comparison between decorator mode and bridge mode

    • The same point is achieved by encapsulating other objects. Similar to the object adapter, it is sometimes called semi decorative design mode

    • There is no primary and secondary difference between the decorator and the decorated. The bridge and the bridged are equal. The bridge can be interchanged without inheriting from the same parent class

      For example, in the example, Phone can hold Color, or Color can hold Phone

    • The bridge mode does not use the same interface; The decoration pattern is decorated with the same interface, which is defined in the parent class

       

       

 

 

 

 

 

 

 

Episode 3 Stream IO stream in JDK source code - Application of decorator design pattern

Introduction: Explanation - application scenario of decorator design pattern in JDK source code

  • Abstract Component: InputStream

    • Specification for defining decoration methods

     

  • Concretecomponent: FileInputStream, ByteArrayInputStream

    • The specific implementation of Component, that is, the specific object we want to decorate

     

  • Decorator: FilterInputStream

    • Define the behavior specification of the specific decorator, have the same interface with the Component role, and hold the instance reference of the Component object
    • Bicycle components have names and prices

     

  • Concrete decorator: BufferedInputStream, DataInputStream

    • Be responsible for decorating additional functions for component objects
    • Such as horn, explosion-proof tire

  • Application scenario


//Added Buffer buffer function
InputStream inputStream = new BufferedInputStream(new FileInputStream(""));






 

Episode 4 here comes the franchisee - the agent design mode you need to master

Introduction: explain the agent design mode and let the agent help you complete the work

  • Proxy Pattern

    • Providing a proxy for other objects to control access to this object belongs to structural mode.

    • The client does not directly call the actual object, but indirectly calls the actual object by calling the proxy

       

 

  • Application scenario

    • Major digital franchise stores and agents sell corresponding products, and the agents hold the real power of attorney
    • The client does not want to directly access the actual object, or it is difficult to access the actual object. It completes the indirect access through a proxy object
    • Want to do some control or enhance functions when accessing a class

  • role

    • Subject: abstract interface, an abstract interface to be implemented by both real objects and proxy objects, such as selling digital products
    • Proxy: it contains references to real objects, so that you can operate real objects at will, such as proxy franchise stores
    • RealProject: real objects, like manufacturers selling digital products

 

 

 

 

 

 

Episode 5 here comes the franchisee - the agent design mode you need to master

Introduction: explain the agent design mode and let the agent help you complete the work "part 2"

  • Business requirements


Droplet classroom-Lao Wang wants to open a digital canteen to prepare for his retirement. He acts as an agent for mobile phones and computers of major manufacturers and uses the agent design mode to help him realize it
​
Subject Selling mobile phones
​
RealProject The core of apple and Huawei manufacturers is to sell mobile phones, but they are not familiar with the location
​
Proxy Laowang digital store: agent selling mobile phones, additional address selection, increasing advertising, etc
​
​
Coding practice




/**
 * Method of extracting public information
 */
public interface DigitalSell {
​
    void sell();
}
​
​
/**
 * Xiaodi classroom, vision: make technology no longer difficult to learn
 *
 * @Description Real object
 * @Author Second in command D
 * @Remark If you have any questions, please contact me directly. Source code - Notes - Technical Exchange Group
 * @Version 1.0
 **/
​
public class DigitalSellReal implements DigitalSell{
​
    @Override
    public void sell() {
​
        System.out.println("Sales of Huawei mobile phones");
    }
}
​
​
/**
 * Xiaodi classroom, vision: make technology no longer difficult to learn https://xdclass.net
 *
 * @Description Proxy object, added function
 * @Author Second in command D
 * @Remark If you have any questions, please contact me directly. Source code - Notes - technical exchange group wechat xdclass6
 * @Version 1.0
 **/
​
public class DigitalSellProxy implements DigitalSell {
​
    private DigitalSell realObj = new DigitalSellReal();
​
    @Override
    public void sell() {
​
        makeAddress();
        realObj.sell();
        makeAD();
    }
    private void makeAddress(){
        System.out.println("An address with high traffic");
    }
    private void makeAD(){
        System.out.println("Advertising");
    }
​
}
​
//use
public static void main(String[] args) {
​
        //Behavior of real objects
        DigitalSell realObj = new DigitalSellReal();
        realObj.sell();
​
        //Behavior of proxy objects
        DigitalSell proxy = new DigitalSellProxy();
        proxy.sell();
    }
  • advantage

    • You can do some control or add functions when accessing a class
    • The operation agent class does not need to modify the original source code, conforms to the opening and closing principle, and the system has good flexibility and scalability
  • shortcoming

    • Increase system complexity and call link

  • There are static agent and dynamic agent

    • There are also many ways of dynamic proxy, such as cglib and jdk. You can see the spring5 module of the new Springboot theme

     

  • Difference between and decorator mode:

    • Agent mode mainly has two functions

      • Protect target object
      • Enhance the target object, similar to decoration mode

 

 

 

 

 

6 - how many third-party designs do you know about them?

Introduction: explain the introduction and application scenario of appearance design mode

  • Facade Pattern

    • Facade mode hides the complexity of the system and provides an interface for the client to access the system
    • A high-level interface is defined, which makes the system easier to use

 

 

  • Application scenario

    • In the view of outsiders, Xiaodi classroom Lao Wang is responsible for message push, which seems very easy, but they don't know how complex it is. How long does Lao Wang work overtime to output a unified interface? As long as it is easy to operate, complex things can be completed
    • Develop MVC three-tier architecture, and use interface interface between layers of data access layer and business logic layer, business logic layer and presentation layer to interact, without worrying about internal logic and reducing coupling
    • Most third-party SDK s use appearance mode. There is only one unified high-level interface through one appearance class, that is, the interface of the whole system, which shields users from many implementation details. Appearance mode is often used as a common means to encapsulate API
    • For the expansion of complex and difficult to maintain old systems, the appearance design mode can be used
    • It is necessary to provide an external access interface for a complex module or subsystem. The external access to the subsystem only needs black box operation

 

  • role

    • Facade: the client can call the method of this role. This facade method knows the functions and actual calls of multiple subsystems
    • Subsystem role: each subsystem can be called directly by the client. The subsystem does not know the existence of the facade,

 

 

 

 

 

 

 

 

 

 

Episode 7 case practice - Application of appearance design mode in multi-channel message push

Introduction: explain the case practice of appearance design mode

  • Business requirements


In the eyes of outsiders, Xiaodi classroom-Lao Wang is in charge of news push. It seems very easy, but they don't know how complicated it is
​
We need to connect wechat messages, email messages, nail messages, etc. Lao Wang works overtime for a long time without a girlfriend before outputting a unified interface. As long as it is easy to operate, complex things can be completed
​
Use the appearance design mode to help Lao Wang complete this requirement

 

  • advantage

    • It reduces the interdependence of the system and improves the flexibility

    • Comply with the principle of dependency inversion

      • For interface programming, it depends on abstraction rather than concrete
    • According to Dimitri's law

      • The least known principle is that one entity should interact with other entities as little as possible
  • shortcoming

    • Link and system classes are added
    • It doesn't conform to the principle of opening and closing. If new logic is added, the facade appearance class needs to be modified

 

 

 

 

 

 

Episode 8 how much do you know about Flyweight Pattern

Introduction: explain the introduction and application scenarios of Xiangyuan design mode

  • Flyweight pattern

    • It belongs to structural mode, which is mainly used to reduce the number of objects created to reduce memory consumption and improve performance. It provides a way to reduce the number of objects and improve the object structure required by the application.
    • Meta mode attempts to reuse existing homogeneous objects, and if no matching object is found, a new object is created

 

  • Application scenario

    • String in JAVA, if there is one in the string constant pool, it will be returned. If there is no one, a string will be created and saved in the string constant pool
    • Database connection pool, thread pool, etc
    • If the system has a large number of similar objects or needs a buffer pool, you can use the shared element design pattern, that is, the pooling technology
    • If it is found that a large number of fine-grained instances of an object are generated, and these instances are basically the same except for a few parameters, if those shared parameters are moved outside the class and passed in during method call, the number of instances can be reduced by sharing objects

 

  • Internal state

    • It will not change with the change of environment and can be shared
  • External state

    • It cannot be shared. It changes with the change of the environment, so the external state is maintained by the client (because the change of the environment is generally caused by the client)

 

  • role

    • Abstract meta role: Specifies the method that must be implemented for the specific meta role, and the external state is passed in the form of parameters through this method
    • Concrete meta role: the method to implement the provisions of abstract role. If there is an internal state, it is responsible for providing storage space for the internal state.
    • Xiangyuan factory role: responsible for creating and managing Xiangyuan roles. To achieve the purpose of sharing, the realization of this role is the key
    • The client also needs to maintain the corresponding state of all external roles

 

 

 

 

 

 

 

 

 

Episode 9 Lao Wang's website outsourcing - Xiangyuan design mode case practice, advantages and disadvantages

Introduction: explain the case practice, advantages and disadvantages of Xiangyuan design mode

  • Case practice


Droplet classroom-In order to increase his income, Lao Wang began to take over the outsourcing project and developed one AI Website template can automatically generate different types of websites according to different customer needs
 E-commerce, enterprise product display, information flow, etc.
​
It's troublesome when deploying. Does each machine rent cloud servers and buy independent domain names
​
These websites have high structural similarity and are not high traffic websites. You can first share server resources and reduce the cost of server resources, similar to virtual machines or Docker




public class Company {
​
    private String name;
​
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
​
    public Company(){}
​
    public Company(String name){
        this.name = name;
    }
}
//Abstract interface,
public abstract class CloudWebSite {
​
    public abstract void run(Company company);
​
}
​
/**
 * Xiaodi classroom, vision: make technology no longer difficult to learn https://xdclass.net
 *
 * @Description
 * @Author Second in command D
 * @Remark If you have any questions, please contact me directly. Source code - Notes - technical exchange group wechat xdclass6
 * @Version 1.0
 **/
public class ConcreteWebSite extends CloudWebSite {
    private String category;
​
    public  ConcreteWebSite(String category){
        this.category = category;
    }
​
    @Override
    public void run(Company company) {
        System.out.println("Website classification:"+category+", Company:"+company.getName());
​
    }
}
​
​
//factory
public class WebSiteFactory {
    /**
     * map The key inside is classification
     */
    private Map<String,ConcreteWebSite> map = new HashMap<>();
    /**
     * Get classified sites according to key
     * @param category
     * @return
     */
    public CloudWebSite getWebSiteByCategory(String category){
​
        if(map.containsKey(category)){
            return map.get(category);
        }else {
            ConcreteWebSite site = new ConcreteWebSite(category);
            map.put(category,site);
            return site;
        }
    }
    /**
     * Get the number of classifications
     * @return
     */
    public int getWebsiteCategorySize(){
        return map.size();
    }
​
}
​
​
//use
public static void main(String[] args) {
​
        WebSiteFactory factory = new WebSiteFactory();
​
        CloudWebSite companySite1 =  factory.getWebSiteByCategory("Enterprise official website");
        companySite1.run(new Company("Droplet classroom"));
​
        CloudWebSite companySite2 =  factory.getWebSiteByCategory("Enterprise official website");
        companySite2.run(new Company("Xuyao classroom"));
​
        CloudWebSite byteDanceSite =  factory.getWebSiteByCategory("information flow");
        byteDanceSite.run(new Company("Byte runout"));
​
        CloudWebSite ucNews =  factory.getWebSiteByCategory("information flow");
        ucNews.run(new Company("Youshi Technology"));
​
        System.out.println("Total site categories:" +factory.getWebsiteCategorySize());
​
​
    }


  • advantage

    • It greatly reduces the creation of objects, reduces the occupation of program memory and improves efficiency

     

  • shortcoming

    • It increases the complexity of the system and needs to separate the internal state from the external state

 

  • Pay attention to the division of internal state and external state, otherwise thread safety problems may be caused, which must be controlled by a factory class

 

  • Differences between shared element design pattern and prototype and singleton pattern

    • Prototype design pattern is to specify the type of objects to be created, and then create new objects by copying these prototypes.
    • The singleton design pattern ensures that there is only one instance of a class

 

 

 

Dry goods document

 

 

Tags: Python Java Programming Big Data Design Pattern Interview

Posted by Russia on Sun, 01 May 2022 23:20:46 +0300