java设计模式-享元模式

享元模式

基本介绍

1、享元模式(flyweight Pattern),也叫作蝇量模式:运用在共享技术有效的支持大量细粒度的对象。
2、常用语系统底层开发,解决系统的性能问题。像 数据库连接,里面都是创建好的连接对象,在这些连接对象中有我们需要的则直接拿来用,
避免重新创建,入股偶没有我们需要的,则创建一个。
3、享元模式能够解决重复对象的内存浪费的问题,当系统中有大量相似对象,需要缓冲池时,不需要总是创建新对象,可以从缓冲池里面那拿,
这样可以降低系统内存,同时提高效率。
4、享元模式经典的应用常见就是池技术,String常量池,数据库连接池,缓冲池等等都是享元模式的应用,享元模式是池技术的重要实现方式。

原理图
java设计模式-享元模式_第1张图片

1、FlyWeight是抽象的享元校色,他是产品的抽象类,同时定义出对象的外部状态内部状态
2、ConcreteFlyWeight具体的享元模式角色,是具体的产品类,实现抽象校色定义相关业务。
3、UnsharedConcreteFlyWeight是不可共享的角色。 一般不会出现在向原工厂。
4、FlyWeightFactory 向原工厂类,用于构建一个容器池(集合),同事提供从池中获取对象方法。

内部状态和外部状态

比如围棋、五子棋、跳棋,它们都有大量的棋子对象,围棋和五子棋只有黑白两色,跳棋颜 色多 一
点 ,所以棋子颜色就是棋子的内部状态;而各个棋子之间的差别就是位置的不同 ,当我们落子后
落子颜色是定的,但位置是变化的,所以棋子坐标就是棋子的外部状态

举个例子:围棋理 论上有 361 个空位可以放棋子 ,每盘棋都有可能有两三百个棋子对象产生,因为内存空间有限,
一台服务器很难支持更多的玩家玩围棋游戏,如果用享元模式来处理棋子,那么棋子对象就可以减少到只有两个实例,
这样就很好的解决了对象的开销问题

1、享元模式提出两个要求:细粒度共享对象。这里就涉及到内部状态和外部状态了,即将对象的信息分为两个部分:内部状态和外部状态。
2、内部状态指对象共享出来的信息,存储在向原对象内部切不会随环境的改变而改变。
3、外部状态指对象的意义来的一个标记,是随环境改变而改变,不可共享的状态。
java设计模式-享元模式_第2张图片

public abstract class WebSite {
    //抽象方法
    public abstract  void use(User user);
}
@Data
public class User {
    private String name;
    public User(String name) {
        this.name = name;
    }
}
@Slf4j
public class ConcreteWebSite extends WebSite {
    //共享的部分,内部状态
    //网站发布的形式(类型)
    private String type = "";
    public ConcreteWebSite(String type) {
        this.type = type;
    }
    @Override
    public void use(User user) {
        log.info("正在使用的网站:{},使用者是:{}",type,user.getName());
    }
}
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 pool.get(type);
    }
    //获取网站分类的总数(池中有多少个世纪网站类型)
    public int getWebSiteCount(){
        return pool.size();
    }
}
@Slf4j
public class Client {
    public static void main(String[] args) {
        //创建一个工厂类
        WebSiteFactory factory=new WebSiteFactory();
        //创建一个以新闻形式发布的网站
        WebSite webSite=factory.getWebSiteCategory("新闻");
        webSite.use(new User("张三"));
        WebSite webSite1=factory.getWebSiteCategory("博客");
        webSite1.use(new User("张三1"));
        WebSite webSite2=factory.getWebSiteCategory("博客");
        webSite2.use(new User("张三2"));
        WebSite webSite3=factory.getWebSiteCategory("博客");
        webSite3.use(new User("张三3"));
        WebSite webSite4=factory.getWebSiteCategory("博客");
        webSite4.use(new User("张三4"));
        int webSiteCount = factory.getWebSiteCount();
        log.info("当前池中有{}个网站分类",webSiteCount);
    }
}

打印结果:

正在使用的网站:新闻,使用者是:张三  
正在使用的网站:博客,使用者是:张三1  
正在使用的网站:博客,使用者是:张三2  
正在使用的网站:博客,使用者是:张三3  
正在使用的网站:博客,使用者是:张三4  
当前池中有2个网站分类

享元模式在jdk源码中的使用(Integer

public class IntegerTest {
    public static void main(String[] args) {
        //如果Integer.valueOf(x) x在 -128 --- 127之间,使用的是享元模式
        // 如果不在范围内,则仍然new一个新对象

        //小结:
        //1、在valueOf方法中,先判断值是否在IntegerCache中存在,如果不在,则新创建新的对象,否则直接从cache缓存池中取出返回,
        //2、valueOf方法, 就使用到了享元模式
        //3、如果使用到了valueOf方法得到一个Integer实例,范围在-128 - 127,直行速度比new快
        Integer x = Integer.valueOf(127);
        Integer y = new Integer(127);
        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
        System.out.println("=============================");
        Integer x1 = Integer.valueOf(200);
        Integer y1 = Integer.valueOf(200);
        System.out.println(x1==y1);//false
    }
}

源码分析

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

//源码继续分析
private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];
    static {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
                // If the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;
        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);
        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }
    private IntegerCache() {}
}

使用注意事项

1、在享元模式这样理解,“享”就表示的共享,“元”表示对象。
2、系统中有大量对象,这些对象小号大量内存,并且对象的状态大部分可以外部化时,我们就可以考虑选用享元模式。
3、用唯一标识符判断,如果在内存中有,则返回这个唯一标识码所表示的对象。用HashMap/HashTable存储。
4、享元模式大大减少了对象的创建,降低了程序没存的占用,提高效率
5、享元模式提高了系统的复杂度。需要分离出内部状态和外部状态,而外部状态具有固化特性,不应该随着内部状态二改变,这是我们 使用享元模式需要注意的地方
6、使用享元模式时,注意划分内部状态和外部状态,并且需要有一个工厂类加以控制。
7、享元模式进店的应用场景就是 需要缓冲池的场景,比如String常量池,数据里连接池。

你可能感兴趣的:(设计模式,java,设计模式,享元模式)