享元模式Flyweight Pattern-23种常用设计模式快速入门教程
1.享元模式定义
享元模式是一种结构型设计模式,它使用共享物件,用来尽可能减少内存中对象的数量,以减少内存开销和提高性能。
2.享元模式优点
它可以减少内存中对象的数量,从而减少内存开销,提高性能。
3.享元模式缺点
它将产生大量小对象,这些对象占用了更多的空间,而且实现享元模式的代码比较复杂,它把系统的重心从应用本身转移到了内存管理上。
4.享元模式示例代码
传统设计模式讲解时使用的示例代码,大都采用与读者日常生活接解的业务系统没有多大关联关系。以致大部分读者无法做到学以致用,学完就忘记。本文采用使用日常生活中随处可见的优惠券业务来编写实现代码
//定义享元模式抽象享元类
public abstract class CouponFlyweight {
public abstract void showDiscount();
}
//享元模式具体享元类
public class ConcreteFlyweight extends CouponFlyweight {
private String type;
private double discount;
public ConcreteFlyweight (String type) {
this.type = type; if (type.equals("discount")) {
this.discount = 0.8;
}
}
@Override
public void showDiscount() {
System.out.println(type + " coupon, discount: " + discount);
}
}
//享元工厂类
public class CouponFlyweightFactory {
private static Map<String, CouponFlyweight> pool = new HashMap<>();
public static CouponFlyweight getFlyweight(String type) {
CouponFlyweight flyweight = null;
if (pool.containsKey(type)) {
flyweight = pool.get(type);
}
else {
flyweight = new ConcreteFlyweight(type);
pool.put(type, flyweight);
}
return flyweight;
}
}
//享元模式客户端使用
public class Client {
public static void main(String[] args) {
CouponFlyweight couponFlyweight = CouponFlyweightFactory.getFlyweight("discount");
couponFlyweight.showDiscount();
}
}