0

关于工厂模式

 2 years ago
source link: https://www.v2ex.com/t/816721
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Java

关于工厂模式

  taofoo · 3 小时 4 分钟前 · 236 次点击

之前在 这里 看到了一个关于享元模式的代码。

import java.util.HashMap;
 
public class ShapeFactory {
   private static final HashMap<String, Shape> circleMap = new HashMap<>();
 
   public static Shape getCircle(String color) {  // 这里没有看懂, 既然已经知道返回的是一个 Circle ,为什么还要转成 Shape
      Circle circle = (Circle)circleMap.get(color);
      return circle;
   }
}

...
// 使用的代码,又把 Shape 转成了 Circle
 (Circle)ShapeFactory.getCircle(getRandomColor());

不过,我想说的可能脱离了享元模式。在 ShapeFactory 中 getCircle() 很明确的指出获得的是 Circle ,为什么还要转换成 Shape,用的时候再转换成 Circle ,这样做的目的是什么呢?我没有想明白。(另外 Circle 实现了 Shape,再 Circle 向上转型为 Shape 的时候不会出现问题,那么 Circle 可以直接视为 Shape )。就 ShapeFactory 而言,抽象和多态的目的在于以后可能会出现额外的 Shape 。所以不太明白,getCircle()方法的意义。

总结下问题:1. 抽象的 ShapeFactory 为什么会有 getCircle()方法。(可能是方便) 2.getCircle()返回的是 Shape (既然明确了是 Circle,为什么还要转成 Shape )


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK