//20210120
写在前面:刚期末考试完,考了面向对象,里边儿有23个设计模式,我寻思着考完挨个儿实现一下,本文实现适配者模式
核心思想
- 如果在一个类中频繁创建内容相同的对象,则会使内存占用很高,如果在产品中使用此方法,则会占用大量内存,如果将内容相同的对象共享,则能够节省很多资源,享元模式应运而生,正如其名,它提供可共享的对象
程序源代码如下:
//享元抽象父类
public abstract class FlyWeight {
//内部状态
public String intrinsic;
//外部状态
protected final String extrinsic;
//要求享元角色必须接受外部状态
public FlyWeight(String extrinsic){
this.extrinsic = extrinsic;
}
//定义业务操作
public abstract void operate (int extrinsic);
public String getIntrinsic(){
return intrinsic;
}
public void setIntrinsic(String intrinsic){
this.intrinsic = intrinsic;
}
}
//具体享元(继承父类)
public class ConcreteFlyWeight extends FlyWeight{
//接受外部状态
public ConcreteFlyWeight(String extrinsic){
super(extrinsic);
}
//根据外部状态进行逻辑处理
@Override
public void operate(int extrinsic) {
System.out.println("具体FlyWeight:"+ extrinsic);
}
}
//非共享享元
public class UnsharedConcreteFlyWeight extends FlyWeight{
public UnsharedConcreteFlyWeight(String extrinsic){
super(extrinsic);
}
@Override
public void operate(int extrinsic) {
System.out.println("不共享的具体FlyWeight:"+extrinsic);
}
}
//享元工厂
public class FlyWeightFactory {
//定义一个池容器
private static HashMap<String ,FlyWeight> pool = new HashMap<>();
//享元工厂
public static FlyWeight getFlyWeight(String extrinsic){
FlyWeight flyWeight = null;
if(pool.containsKey(extrinsic)){//如果池中有该对象
flyWeight = pool.get(extrinsic);
System.out.print("已有"+extrinsic+" 直接从池中取----->");
} else {
//根据外部状态创建享元对象
flyWeight = new ConcreteFlyWeight(extrinsic);
//放入池中
pool.put(extrinsic,flyWeight);
System.out.print("创建" + extrinsic + " 并从池中取出----->");
}
return flyWeight;//工厂生产出一个享元
}
}
//测试主类
public class Main {
public static void main(String[] args) {
int extrinsic = 22;
FlyWeight flyWeight_1 = FlyWeightFactory.getFlyWeight("X");
flyWeight_1.operate(++extrinsic);
FlyWeight flyWeight_2 = FlyWeightFactory.getFlyWeight("Y");
flyWeight_2.operate(++extrinsic);
FlyWeight flyWeight_3 = FlyWeightFactory.getFlyWeight("Z");
flyWeight_3.operate(++extrinsic);
FlyWeight flyWeight_re_1 = FlyWeightFactory.getFlyWeight("X");
flyWeight_re_1.operate(++extrinsic);
FlyWeight unshareFlyWeight = new UnsharedConcreteFlyWeight("X");
unshareFlyWeight.operate(++extrinsic);
}
}
- 输出如下
以上
希望对大家有所帮助