工厂方法模式-Factory Pattern

基本概念

工厂方法模式,定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。

结构图


上图摘自《大话设计模式》

应用场景

当你使用了简单工厂模式,再进行扩展时,本来是需要修改工厂类的,但这会违背开放-封闭原则,因此需要把简单工厂的内部逻辑判断转移到客户端来实现,达到对扩展开放的目的。

源码示例

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值