package designpattern.flyweight; public interface Chessman { abstract void position(String position); }
具体棋子类:
package designpattern.flyweight; public class ConcreteChessman implements Chessman { String color; public ConcreteChessman(String color) { this.color = color; } @Override public void position(String position) { System.out.println(color + "棋下在:" + position); } }
棋子工厂类:
package designpattern.flyweight; import java.util.HashMap; import java.util.Map; public class ChessmanFactory { Map<String, Chessman> map = new HashMap<>(); public Chessman getChessman(String color) { if (map.containsKey(color)) { return map.get(color); } else { Chessman chessman = new ConcreteChessman(color); map.put(color, chessman); return chessman; } } }
客户端:
package designpattern.flyweight; public class Client { public static void main(String[] args) { ChessmanFactory factory=new ChessmanFactory(); Chessman cc1= factory.getChessman("黑"); cc1.position("右上星位"); Chessman cc2= factory.getChessman("白"); cc2.position("天元"); Chessman cc3= factory.getChessman("黑"); cc3.position("右上目外"); } }
结果输出:
黑棋下在:右上星位
白棋下在:天元
黑棋下在:右上目外
上面的后半句我没太看明白,所以留给大家自己理解吧。
原文:https://www.cnblogs.com/imoqian/p/13974400.html