赞
踩
概念:是池技术的重要实现方式,可以降低大量重复的、细粒度的类在内存中的开销。
享元模式是以共享的方式高效地支持大量的细粒度对象。
享元对象能做到共享的关键是区分内部状态和外部状态。
用一个下围棋的例子来帮助大家理解。围棋只有黑棋和白棋,不必每次都创建新对象,这是内部状态。而棋子的落点可以作为外部状态传进来。
- public abstract class Flyweight {
- void put(Flyweight position) {
- }
- int getX() {
- return 0;
- }
- int getY() {
- return 0;
- }
- }
-
- public class ChessFlyweight extends Flyweight {
- private String color;
- public ChessFlyweight(String color) {
- this.color = color;
- }
- @Override
- public void put(Flyweight position) {
- if (!(position instanceof PositionFlyweight)) {
- System.out.println("位置错误。");;
- }
- System.out.println("在位置:" + "("+ position.getX() + "," + position.getY() +"), 放置了" + color + "棋子");
- }
- }
-
- public class PositionFlyweight extends Flyweight {
- private final int x;
- private final int y;
- public PositionFlyweight(int x, int y) {
- this.x = x;
- this.y = y;
- }
- @Override
- public int getX() {
- return x;
- }
- @Override
- public int getY() {
- return y;
- }
- }
-
- public class FlyweightFactory {
- private static final Flyweight WHITE = new ChessFlyweight("白色");
- private static final Flyweight BLACK = new ChessFlyweight("黑色");
- public static Flyweight getChess(String color) {
- if (color.equals("白色")) {
- return WHITE;
- } else if (color.equals("黑色")) {
- return BLACK;
- }
- return null;
- }
- }
-
- public class Demo {
- public static void main(String[] args) {
- Flyweight whiteChess1 = FlyweightFactory.getChess("黑色");
- Flyweight whiteChess2 = FlyweightFactory.getChess("黑色");
- Flyweight blackChess1 = FlyweightFactory.getChess("白色");
- Flyweight blackChess2 = FlyweightFactory.getChess("白色");
- whiteChess1.put(new PositionFlyweight(1, 1));
- blackChess1.put(new PositionFlyweight(2, 2));
- whiteChess2.put(new PositionFlyweight(3, 3));
- blackChess2.put(new PositionFlyweight(4, 4));
- }
- }
如果大家需要视频版本的讲解,欢迎关注我的B站。
十三、设计模式之享元模式讲解
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。