定义一个创建对象的接口
public interface Shape {
void draw();
}
子类实现接口
public class Rectangle implements Shape{
@Override
public void draw() {
System.out.println("Inside Rectangle :: Draw()");
}
}
public class Cricle implements Shape{
@Override
public void draw() {
System.out.println("Inside Cricle :: draw()");
}
}
public class Square implements Shape{
@Override
public void draw() {
System.out.println("Inside Square :: Draw()");
}
}
建立工厂类决定实例化哪一个子类
public class ShapeFactory {
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
//equalsIgnoreCase 与另一个String比较不考虑大小写
if(shapeType.equalsIgnoreCase("CRICLE")){
return new Cricle();
}else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}
调用
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape1 = shapeFactory.getShape("CRICLE");
shape1.draw();
Shape shape2 = shapeFactory.getShape("RECTANGLE");
shape2.draw();
Shape shape3 = shapeFactory.getShape("SQUARE");
shape3.draw();
}
}
输出