享元模式(FlyWeight)

场景:

内存属于稀缺资源,不要随便浪费。如果有很多个完全相同或相似的对象,我们可以通过享元模式,节省内存。

核心:

享元模式以共享的方式高效地支持大量细粒度对象的重用。

享元对象能做到共享的关键是区分了内部状态和外部状态。

   内部状态:可以共享,不会随便环境变化而变化

   外部状态:不可以共享,会随环境变化而变化。

享元模式实现:

FlyweightFactory享元工厂类

   创建并管理享元对象,享元池一般设计成键值对

FlyWeight抽象享元类

   通常是一个接口或抽象类,声明公共方法,这些方法可以向外界提供对象的内部状态,设置外部状态。

ConcreteFlyWeight具体享元类

   为内部状态提供成员变量进行存储

UnsharedConcreteFlyWeight非共享享元类

   不能被共享的子类可以设计为非共享享元类

享元模式的使用一般要工厂模式搭配起来。

 

/FlyWeight抽象享元类

interface ChessFlyWeight{

   void setColor(String color);

   String getColor();

   void disPlay(Coordinate coo);

}

//UnsharedConcreteFlyWeight非共享享元类

class Coordinate{

   privateintx,y;

   public Coordinate(int x,int y){

      super();

      this.x = x;

      this.y = y;

   }

   publicint getX() {

      returnx;

   }

   publicvoid setX(int x) {

      this.x = x;

   }

   publicint getY() {

      returny;

   }

   publicvoid setY(int y) {

      this.y = y;

   }

}

//ConcreteFlyWeight具体享元类

class CoocreteChess implements ChessFlyWeight{

  

   private String color;

  

   public CoocreteChess(String color){

      super();

      this.color = color;

   }

   publicvoid setColor(String color) {

      this.color = color;

     

   }

   public String getColor() {

     

      returncolor;

   }

 

   publicvoid disPlay(Coordinate coo) {

      System.out.println("棋子颜色"+color);

      System.out.println("棋子位置"+coo.getX()+"--"+coo.getY());

   }

}

//FlyweightFactory享元工厂类

class ChessFlyWeightFactory{

   //享元池

   privatestatic Map<String,ChessFlyWeight> map = new HashMap<String, ChessFlyWeight>();

   

    publicstatic ChessFlyWeight getChess(String color){

       if(map.get(color)!=null){

          returnmap.get(color);

       }else{

          ChessFlyWeight cfw = new CoocreteChess(color);

          map.put(color, cfw);

          return cfw;

       }

    }

}

publicclass Client {

   publicstaticvoid main(String[] args) {

      ChessFlyWeight cf1= ChessFlyWeightFactory.getChess("黑色");

      ChessFlyWeight cf2= ChessFlyWeightFactory.getChess("黑色");

       System.out.println(cf1);

       System.out.println(cf2);

       System.out.println("增加外部状态的位置!");

       cf1.disPlay(new Coordinate(12, 12));

       cf2.disPlay(new Coordinate(12, 13));

      

   }

}

 

优点:

   极大减少了内存对象的数量

   相同或相似对象内存中只存一份,极大节约资源,提高系统性能

   外部状态相对独立,不影响内部状态

缺点:

模式较复杂,使逻辑复杂化

为了节省内存,共享了内存状态,分离出外部状态,而读取外部状态使运行时间变长。用时间换取空间。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值