设计模式-结构型之享元(flyweight)模式

定义

  • 通过尽量共享实例来避免 new 出实例。

使用场景

  • 大范围使用,可以使用该模式达到共享。
  • 举例:数据库连接池、线程池等。

UML图

设计模式-结构型之享元(flyweight)模式_第1张图片

代码实现

// 共享对象
public class Flyweight {

    private String name;

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

    public void method(){
        System.out.println("共享对象的方法");
    }
}
//池子工厂
public class FlyweightFactory {

    private Map<String,Flyweight> flyweightMap = new HashMap<>();

    //单例
    private static FlyweightFactory factory = new FlyweightFactory();

    //私有构造
    private FlyweightFactory(){}

    //公有获取单例
    public static FlyweightFactory getFacttory(){
        return factory;
    }

    //获取共享对象: 使用synchronized 保证线程安全
    public synchronized Flyweight getFlyweight(String key){
        Flyweight flyweight = flyweightMap.get(key);
        //如果没有则创建并放入池子
        if(flyweight == null){
            flyweight = new Flyweight(key);
            flyweightMap.put(key,flyweight);
        }
        return flyweight;
    }

    //池子元素总数
    public int size(){
        return flyweightMap.size();
    }
}

public class Client {
    public static void main(String[] args) {
        FlyweightFactory factory = FlyweightFactory.getFacttory();
        Flyweight flyweight = factory.getFlyweight("共享");
        flyweight.method();
        factory.getFlyweight("共享2");
        //池子中已有,无需再创建
        factory.getFlyweight("共享");
		//池中只有两个实例
        int size = factory.size();
    }
}

总结

  • 通过尽量共享实例来避免 new 出实例。
  • 减少new 实例,达到减少对资源的占用,通过共享直接从池中获取,不需创建,大大提升程序效率。

你可能感兴趣的:(Design,Patterns)