Create mode -- Factory method
程序员文章站
2022-03-14 13:50:44
...
1 工厂方法模式
2
interface Shape{
public void draw();
}
class Rectangle implements Shape{
@Override
public void draw() {
System.out.println("Draw rectangle");
}
}
class Square implements Shape{
@Override
public void draw() {
System.out.println("Draw square");
}
}
class ShapeFactory{
public Shape productShape(String name){
if (name.isEmpty()){
return null;
}
if (name.equals("rectangle")){
return new Rectangle();
}else if(name.equals("square")){
return new Square();
}
return null;
}
}
public class Test{
public static void main(String[] args){
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape = shapeFactory.productShape("rectangle");
shape.draw();
Shape shape1 = shapeFactory.productShape("square");
shape1.draw();
}
}