基本概念
工厂方法模式,定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
结构图
上图摘自《大话设计模式》
应用场景
当你使用了简单工厂模式,再进行扩展时,本来是需要修改工厂类的,但这会违背开放-封闭原则,因此需要把简单工厂的内部逻辑判断转移到客户端来实现,达到对扩展开放的目的。
源码示例
1.创建Shape接口
package com.spook.factory;
/**
* Shape接口
*/
public interface Shape {
public void draw();
}
2.创建Circle类,实现Shape接口
package com.spook.factory;
/**
* Circle类
*/
public class Circle implements Shape {
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("draw Circle");
}
}
3.
创建Rectangle类,实现Shape接口
package com.spook.factory;
/**
* Rectangle类
*/
public class Rectangle implements Shape {
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("draw Rectangle");
}
}
4.创建Square类,实现Shape接口
package com.spook.factory;
/**
* Square类
*/
public class Square implements Shape {
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("draw Square");
}
}
5.创建ShapeFactory工厂接口
package com.spook.factory;
/**
* 工厂接口
*/
public interface ShapeFactory {
public Shape creatShape();
}
6.创建CircleFactory工厂类,实现ShapeFactory接口
package com.spook.factory;
/**
* Circle工厂类
*/
public class CircleFactory implements ShapeFactory {
@Override
public Shape creatShape() {
// TODO Auto-generated method stub
return new Circle();
}
}
7.创建RectangleFactory工厂类,实现ShapeFactory接口
package com.spook.factory;
/**
* Rectangle工厂类
*/
public class RectangleFactory implements ShapeFactory {
@Override
public Shape creatShape() {
// TODO Auto-generated method stub
return new Rectangle();
}
}
8.创建SquareFactory工厂类,实现ShapeFactory接口
package com.spook.factory;
/**
* Square工厂类
*/
public class SquareFactory implements ShapeFactory {
@Override
public Shape creatShape() {
// TODO Auto-generated method stub
return new Square();
}
}
9.测试类
package com.spook.factory;
/**
* 测试类
*/
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ShapeFactory circleFactory = new CircleFactory();
Shape circle = circleFactory.creatShape();
circle.draw();
ShapeFactory rectangleFactory = new RectangleFactory();
Shape rectangle = rectangleFactory.creatShape();
rectangle.draw();
ShapeFactory squareFactory = new SquareFactory();
Shape square = squareFactory.creatShape();
square.draw();
}
}
运行测试类输出如下内容:
draw Circle
draw Rectangle
draw Square