设计模式学习-用匿名内部类实现工厂模式
程序员文章站
2022-03-09 21:52:44
...
最近看书看到匿名内部类的相关内容,发现采用匿名内部类确实能使工厂模式的设计变得更为合理。
public interface Shape {
public void draw();
}
public interface ShpaeFactory {
public Shape getShape();
}
public class Circle implements Shape {
private Circle(){}
@Override
public void draw() {
System.out.println("draw a circle!");
}
//置为static可以保证该类作为工厂对象的唯一性,同时也提供给外部访问的途径
public static ShpaeFactory shapeFactory = new ShpaeFactory() {
@Override
public Shape getShape() {
return new Circle();
}
};
}
public class Triangle implements Shape {
private Triangle(){}
@Override
public void draw() {
System.out.println("draw a triangle!");
}
//设置为static可以保证该类作为工厂对象的唯一性,同时也提供给外部访问的途径
public static ShpaeFactory shapeFactory = new ShpaeFactory() {
@Override
public Shape getShape() {
return new Triangle();
}
};
}
public class AnotherFactoryDemo {
public static void main(String[] args) {
Drawer drawer = new Drawer();
drawer.drawPicture(Circle.shapeFactory);
drawer.drawPicture(Triangle.shapeFactory);
}
}