我正在学习 Desgin 模式,并在 HERE 中遇到了非常奇怪的示例。如果我们有一个类:
public abstract class AbstractFactory {
abstract Color getColor(String color);
abstract Shape getShape(String shape) ;
}
正如我们所看到的,它有两种创建对象的方法:颜色和形状。这个类是抽象的,所以我们必须创建它的具体实现,所以我们假设我们有:
public class ShapeFactory extends AbstractFactory {
@Override
public Shape getShape(String shapeType){
// I skip implementation to keep post brief
}
@Override
Color getColor(String color) {
return null; // It's useless method in this class!
}
}
第二个实现:
public class ColorFactory extends AbstractFactory {
@Override
public Shape getShape(String shapeType){
return null; // It's useless method in this class!
}
@Override
Color getColor(String color) {
// I skip implementation to keep post brief
}
}
我的问题来了,在这两种情况(具体工厂)中,都有一个完全无用且不应该存在的方法,但是当我们创建 AbstractFactory 类时,我们必须实现这两种方法。在不需要的类中创建无用的方法在编程中不是一种不好的做法吗?是否应该以其他方式完成而不是按照网站建议的方式?
最佳答案
@Michael213 - 您的具体实现不正确。当然他们不遵循抽象工厂模式。抽象工厂谈论产品系列。抽象工厂示例(根据我的假设)将类似于以下代码。您的示例仅使用一种方法将滥用模式并且很快就会崩溃。
我已经回答过类似的问题,请也看看What are the real benefits of using the Abstract Factory in the following example, instead of the factory method?
public abstract class AbstractFactory {
abstract Color getColor(String color);
abstract Shape getShape(String shape) ;
}
/**
* CONCRETE FACTORY1
*/
class HighResolutionFactory extends AbstractFactory{
Color getColor(String color){
return new HighResolutionColor();
}
Shape getShape(String shape){
return new HighResolutionShape();
}
}
/**
* CONCRETE FACTORY2
*/
class LowResolutionFactory extends AbstractFactory{
Color getColor(String color){
return new LowResolutionColor();
}
Shape getShape(String shape){
return new LowResolutionShape();
}
}
class Color{} // ABSTRACT PRODUCT 1
class Shape{} // ABSTRACT PRODUCT 2
class HighResolutionColor extends Color{}// CONCRETE PRODUCT1 FACT 1
class HighResolutionShape extends Shape{}// CONCRETE PRODUCT2 FACT 1
class LowResolutionColor extends Color{}//...
class LowResolutionShape extends Shape{}
关于java - 抽象工厂模式 - 未使用的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46630943/