工厂模式原理图
工厂模式设计步骤
步骤一
创建一个接口(Shape)
package FactoryPattern;
public interface Shape {
void draw();
}
步骤二
创建实现接口的实体类
Circle.class
package FactoryPattern;
public class Circle implements Shape{
public void draw() {
// TODO Auto-generated method stub
System.out.println("Circle");
}
}
Square.class
package FactoryPattern;
public class Square implements Shape{
public void draw() {
// TODO Auto-generated method stub
System.out.println("Sahpe");
}
}
Rectangle.class
package FactoryPattern;
public class Rectangle implements Shape{
public void draw() {
// TODO Auto-generated method stub
System.out.println("Rectangle");
}
}
步骤三
创建一个工厂,生成基于给定信息的实体类的对象。
package FactoryPattern;
public class ShapeFactory {
public Shape getShape(String s){
if(s.equalsIgnoreCase("Circle"))
return new Circle();
else if(s.equalsIgnoreCase("Square"))
return new Square();
else if(s.equalsIgnoreCase("Rectangle"))
return new Rectangle();
else
return null;
}
}
步骤四
使用该工厂,通过传递类型信息来获取实体类的对象。
package FactoryPattern;
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape s1 = shapeFactory.getShape("circle");
s1.draw();
Shape s2 = shapeFactory.getShape("square");
s2.draw();
Shape s3 = shapeFactory.getShape("rectangle");
s3.draw();
Shape s4 = shapeFactory.getShape("angle");
if(s4 != null)
s4.draw();
}
}
结果
Circle
Sahpe
Rectangle