编程知识 cdmana.com

Making up lessons: design mode (21) - Heyuan mode

1. The above summary

「 Make up a missed lesson 」 In progress : Design pattern series

2. The flyweight pattern

2.1 Definition

The flyweight pattern (Flyweight Pattern) It's simple , It also addresses the needs directly , At the same time, it is also an important implementation of pool technology , Let's take a look at its definition :

Use sharing to support large numbers of fine-grained objects efficiently.( Using shared objects can effectively support a large number of fine-grained objects .)

2.2 Generic class diagram

  • Flyweight Abstract meta roles : It's an abstract class of a product , An interface or implementation that defines both the external and internal state of an object .
  • ConcreteFlyweight Specific enjoy yuan role : A specific product class , Implement the business of abstract role definition .
  • unsharedConcreteFlyweight Shareable role : There are no external states or security requirements ( Such as thread safety ) Objects that can't be shared , This object does not normally appear in the Heyuan factory .
  • FlyweightFactory The flyweight factory : Its duties are very simple , That is to construct a pool container , It also provides methods to get objects from the pool .

2.3 General code

Abstract meta roles :

public abstract class Flyweight {
    //  Internal state 
    private String intrinsic;
    //  External state 
    protected final String extrinsic;
    //  It is required that the meta character must accept the external state 
    protected Flyweight(String extrinsic) {
        this.extrinsic = extrinsic;
    }
    //  Define business operations 
    abstract void operate();

    public String getIntrinsic() {
        return intrinsic;
    }

    public void setIntrinsic(String intrinsic) {
        this.intrinsic = intrinsic;
    }
}

Specific enjoy yuan role :

public class ConcreteFlyweight1 extends Flyweight{
    protected ConcreteFlyweight1(String extrinsic) {
        super(extrinsic);
    }

    @Override
    void operate() {

    }
}

public class ConcreteFlyweight2 extends Flyweight{
    protected ConcreteFlyweight2(String extrinsic) {
        super(extrinsic);
    }

    @Override
    void operate() {

    }
}

The flyweight factory :

public class FlyweightFactory {
    //  Define a pool container 
    private static HashMap<String,Flyweight> pool = new HashMap<>();
    //  The flyweight factory 
    public static Flyweight getFlyweight(String Extrinsic) {
        //  The object that needs to be returned 
        Flyweight flyweight = null;
        //  There is no object in the pool 
        if(pool.containsKey(Extrinsic)) {
            flyweight = pool.get(Extrinsic);
        } else {
            //  Create a share object based on the external state 
            flyweight = new ConcreteFlyweight1(Extrinsic);
            //  Put it in the pool 
            pool.put(Extrinsic, flyweight);
        }
        return flyweight;
    }
}

2.4 Advantages and disadvantages

The enjoy pattern is a very simple pattern , It can significantly reduce the number of objects an application creates , Reduce the use of program memory , Enhance program performance , But it also increases the complexity of the system , You need to separate out the external state from the internal state , And the external state has the curing characteristic , It should not change with internal state , Otherwise, the logic of the system will be confused .

3. A small example

The Xiangyuan model is very simple , The general code above is actually a good example , Be similar to Java Medium String Constant pool , Objects that have not been created exist in the pool , If the object exists in the pool, it is directly removed from the pool .

Let me give another simple example , For example, I received a small outsourcing project , Is to do a product display website , Later, his friends also hope to build such a website , But the requirements are different , Of course we can't just copy and paste and have another copy , Some people hope it's a video station , Some people hope it's a graphic station and so on , And because of the funds, we can't rent a space for each website .

This kind of thing is very common in life , But most of the time it's direct copy A code , And make changes , But in the Heyuan mode , There is no such situation ~~~

Website abstract class :

public abstract class WebSite {
    abstract void use();
}

Specific website class :

public class ConcreteWebSite extends WebSite {

    private String name;

    public ConcreteWebSite(String name) {
        this.name = name;
    }

    @Override
    void use() {
        System.out.println(" Website classification :" + name);
    }
}

Network factory class :

public class WebSiteFactory {
    private HashMap<String, WebSite> pool = new HashMap<>();

    // Get site classification 
    public WebSite getWebSiteCategory(String key) {
        if(!pool.containsKey(key)) {
            pool.put(key, new ConcreteWebSite(key));
        }
        return pool.get(key);
    }

    // Get the total number of website categories 
    public int getWebSiteCount() {
        return pool.size();
    }
}

Client client :

public class Client {
    public static void main(String[] args) {
        WebSiteFactory factory = new WebSiteFactory();

        WebSite fx = factory.getWebSiteCategory(" Video station ");
        fx.use();

        WebSite fy = factory.getWebSiteCategory(" Video station ");
        fy.use();

        WebSite fz = factory.getWebSiteCategory(" Video station ");
        fz.use();

        WebSite fa = factory.getWebSiteCategory(" Graphic station ");
        fa.use();

        WebSite fb = factory.getWebSiteCategory(" Graphic station ");
        fb.use();

        WebSite fc = factory.getWebSiteCategory(" Graphic station ");
        fc.use();

        System.out.println(" The total number of website categories is :" + factory.getWebSiteCount());
    }
}

Execution results :

 Website classification : Video station 
 Website classification : Video station 
 Website classification : Video station 
 Website classification : Graphic station 
 Website classification : Graphic station 
 Website classification : Graphic station 
 The total number of website categories is :2

It can be seen that , Although we did 6 Website , But website classification is only 2 individual .

This basically realizes the purpose of sharing objects in the Heyuan mode , But there's actually no difference between objects .

Let's add another user class :

public class User {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Then on WebSite and ConcreteWebSite Of use() Method to modify , add to User Parameters :

public abstract class WebSite {
    abstract void use(User user);
}

public class ConcreteWebSite extends WebSite {

    private String name;

    public ConcreteWebSite(String name) {
        this.name = name;
    }

    @Override
    void use(User user) {
        System.out.println(" Website classification :" + name + "  user :" + user.getName());
    }
}

Finally, revise Client class :

public class Client {
    public static void main(String[] args) {
        WebSiteFactory factory = new WebSiteFactory();

        WebSite fx = factory.getWebSiteCategory(" Video station ");
        fx.use(new User("tom"));

        WebSite fy = factory.getWebSiteCategory(" Video station ");
        fy.use(new User("cat"));

        WebSite fz = factory.getWebSiteCategory(" Video station ");
        fz.use(new User("nginx"));

        WebSite fa = factory.getWebSiteCategory(" Graphic station ");
        fa.use(new User("apache"));

        WebSite fb = factory.getWebSiteCategory(" Graphic station ");
        fb.use(new User("netty"));

        WebSite fc = factory.getWebSiteCategory(" Graphic station ");
        fc.use(new User("jboss"));

        System.out.println(" The total number of website categories is :" + factory.getWebSiteCount());
    }
}

final result :

 Website classification : Video station   user :tom
 Website classification : Video station   user :cat
 Website classification : Video station   user :nginx
 Website classification : Graphic station   user :apache
 Website classification : Graphic station   user :netty
 Website classification : Graphic station   user :jboss
 The total number of website categories is :2

In this way, the internal and external states can be coordinated , Even if we take over the needs of thousands of websites , As long as the requirements are the same or similar , The actual development code is also classified .

版权声明
本文为[Geek excavator]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224085539187i.html

Scroll to Top