在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。定义一个用于创建对象的接口,让子类决定实例化哪个类,解决不同条件下创建不同的类。简单实现如下:
1.创建接口
public interface Shape {
void draw();
}
2.创建各种实体类
public class Triangle implements Shape{
@Override
public void draw() {
System.out.println("draw Triangle");
}
}
public class Circle implements Shape{
@Override
public void draw() {
System.out.println("draw Circle");
}
}
3.创建工厂类
public class ShapeFactory {
public Shape getShape(String type){
if(type == null)
return null;
switch (type){
case "triangle":
return new Triangle();
case "circle":
return new Circle();
default:
return null;
}
}
}
4.测试类
public class FactoryDemo {
public static void main(String[] args) {
ShapeFactory factory = new ShapeFactory();
Shape shape = factory.getShape("circle");
shape.draw();
}
}