10. Flyweight

Flyweight

First, application examples

Small-scale outsourcing projects, client A to make a product showcase site, a friend Customer A feeling well, I hope to do so Products website, but the requirements are a little different:

1) there are customer requirements issued in the form of news

2) there are customer requirements issued in the form of a blog

3) a customer you want to publish in the form of micro-channel public number

Second, Flyweight

1. Basic Introduction

1) Flyweight, also known as fly-volume mode: Use sharing to support a large number of fine-grained objects

2) commonly used in system-level development, to solve the performance problems of the system. Like the database connection pool, which is to create a good connection object, we need to have is directly used to avoid re-create these connection objects, if we do not need, then create a

3) Flyweight waste problem can be solved repetitive object memory, when the system has a large number of similar objects, the buffer pool when needed. You can get directly from the buffer pool, which can reduce system memory, while increasing efficiency.

4) Flyweight application scenario is a classic technique pool, String constant pool, pool database connections, buffer pools.

2. The principle of class diagram

1) FlyWeight Flyweight abstract character, his product is an abstract class, defines both the interface or the internal state and external state of an object.

2) ConcreteFlyWeight Flyweight is a specific role, is a specific product category, to achieve the role of abstract definitions related business

3) UnSharedConcreteFlyWeight is not shared role, generally does not appear in the Flyweight factory.

4) FlyWeightFactory Flyweight factory class for constructing a cell vessel, while providing a method for obtaining an object from the pool.

Internal state is information out of the shared objects stored in the object inside Flyweight environment changes and does not change.

External state refers to a labeled target-dependent, varies with changes in the environment, not shared state.

Third, resolve Flyweight website shows examples

1) analysis chart ideas

2) code implementation

public class Client {
    public static void main(String[] args) {
        // 创建一个工厂类
        WebSiteFactory factory = new WebSiteFactory();

        // 客户要一个以新闻形式发布的网站
        WebSite webSite1 = factory.getWebSiteCategory("新闻");
        webSite1.use(new User("tom"));

        // 客户要一个以博客形式发布的网站
        WebSite webSite2 = factory.getWebSiteCategory("博客");
        webSite2.use(new User("jack"));

        // 客户要一个以博客形式发布的网站
        WebSite webSite3 = factory.getWebSiteCategory("博客");
        webSite3.use(new User("smith"));

        System.out.println("网站的分类共=" + factory.getWebSiteCount());
    }
}
// 网站工厂类,根据需要返回一个网站
public class WebSiteFactory {
    //集合, 充当池的作用
    private HashMap<String, ConcreteWebSite> pool = new HashMap<>();
    
    //根据网站的类型,返回一个网站, 如果没有就创建一个网站,并放入到池中,并返回
    public WebSite getWebSiteCategory(String type) {
        if(!pool.containsKey(type)) {
            //就创建一个网站,并放入到池中
            pool.put(type, new ConcreteWebSite(type));
        }
        return (WebSite)pool.get(type);
    }

    //获取网站分类的总数 (池中有多少个网站类型)
    public int getWebSiteCount() {
        return pool.size();
    }
}
public abstract class WebSite {
    //抽象方法
    public abstract void use(User user);
}

//具体网站
public class ConcreteWebSite extends WebSite {
    //共享的部分,内部状态
    private String type = ""; //网站发布的形式(类型)

    //构造器
    public ConcreteWebSite(String type) {
        this.type = type;
    }

    @Override
    public void use(User user) {
        System.out.println("网站的发布形式为:" + type + " 在使用中 .. 使用者是" + user.getName());
    }
}
public class User {
    private String name;

    public User(String name) {
        super();
        this.name = name;
    }
    public String getName() {
        return name;
    }

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

Fourth, the Flyweight pattern analysis in JDK-Interger of application source code

1) source code analysis

2) Code Description

public class FlyWeight {
    public static void main(String[] args) {
        //如果 Integer.valueOf(x) x 在  -128 --- 127 直接,就是使用享元模式返回,如果不在
        //范围类,则仍然 new 
        
        //小结:
        //1. 在valueOf 方法中,先判断值是否在 IntegerCache 中,如果不在,就创建新的Integer(new), 否则,就直接从 缓存池返回
        //2. valueOf 方法,就使用到享元模式
        //3. 如果使用valueOf 方法得到一个Integer 实例,范围在 -128 - 127 ,执行速度比 new 快
        Integer x = Integer.valueOf(127); // 得到 x实例,类型 Integer
        Integer y = new Integer(127); // 得到 y 实例,类型 Integer
        Integer z = Integer.valueOf(127);//..
        Integer w = new Integer(127);
        
        System.out.println(x.equals(y)); // 大小,true
        System.out.println(x == y ); //  false
        System.out.println(x == z ); // true
        System.out.println(w == x ); // false
        System.out.println(w == y ); // false
        
        Integer x1 = Integer.valueOf(200);
        Integer x2 = Integer.valueOf(200);
        System.out.println("x1==x2" + (x1 == x2)); // false
    }
}

V. Notes

1) Flyweight, "sharing" means Shared "element" indicates an object

2) The system has a large number of objects, which consume a lot of memory, and most of the state of the object can be externalized, we can consider using Flyweight pattern.

3)用唯一标识码判断,如果内存中有,则返回这个唯一标识码所标识的对象,用HashMap/HashTable存储

4)享元模式大大减少了对象的创建,降低了程序内存的占用,提高效率

5)享元模式提高了系统复杂度。使用时,注意划分内部状态和外部状态,并且需要有一个工厂类加以控制

6)经典应用场景是缓冲池的场景,比如String常量池、数据库连接池

Guess you like

Origin www.cnblogs.com/chao-zjj/p/11312176.html