设计模式14——Flyweight设计模式

Flyweight享元设计模式是为了避免大量拥有相同内容的小类重复创建,而使大家共享一个类的模式。Flyweight享元设计模式实质是运用一个简单工厂方法模式,外加一个单类模式实现细粒度原件的共享。享元模式结构如下:

设计模式14——Flyweight设计模式

Flyweight享元设计模式有两个重要概念:

以文字处理软件中对象为例

内部状态intrinsic:可以共享的对象,如相同的字。

外部状态extrinsic:不能共享的对象,如每个字的位置,大小等等。

Flyweight享元设计模式使用对象池存放内部对象,当需要内部对象时首先判断对象池中是否存在,如果存在直接返回,如果不存在创建一个对象放入对象池中返回。

书有书名,作者和价格三个常用的属性,其中作者有可能是同一个人,使用Flyweight享元设计模式的例子代码如下:
class Book{
    private String title;
    private float price;
    private Author author;

    public String getTitle(){
        return title;
    }
    public float getPrice(){
        return price;
    }
    public Author getAuthor(){
        return author;	
    }
}


//将Author作者类设计为可共享的享元
class Author{
    //内部状态
    private String name;

    public String getName(){
        return name;
    }

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


//享元工厂
public class AuthorFactory{
    private static Map<String, Author> authors = new HashMap<String, Author>();

    public static Author getAuthor(String name){
        Author author = authors.get(name);
        if(author == null){
            author = new Author(name);
            authors.put(name, author);
        }
        return author;
    }
}

Flyweight享元设计模式非常适合文字处理软件,因为像文字这种小对象重用的可能性很高,如果不共享对象,就会生成数量巨大的小对象消耗内存,享元模式则可以使重复概率高的对象重用,大大提高程序效率和性能。

享元模式特点:

享元模式基本是单例模式+简单工厂模式。
减少运行时对象实例的个数,节省内存。

 

JDK中享元模式的应用:

java.lang.Integer#valueOf(int)
java.lang.Boolean#valueOf(boolean)
java.lang.Byte#valueOf(byte)
java.lang.Character#valueOf(char)
String常量池

你可能感兴趣的:(设计模式14——Flyweight设计模式)