大话设计模式八:工厂方法模式(雷锋依然在人间)

工厂方法模式是简单工厂模式的抽象和扩展。java

工厂方法模式是由客户端来决定实例化那一个工厂实现类。ide

在简单工厂类中若是要增长功能改动的是工厂类,但在工厂方法模式中要改的就是客户端了,由客户端决定spa

package Factory;

public class MainClass {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		LeiFeng xueLeiFeng = new Undergraduate();
		xueLeiFeng.BuyRice();
		xueLeiFeng.Sweep();
		xueLeiFeng.Wash();
		
		simpleFactory();
		
		factory();
	}

	private static void factory() {
		IFactory factory = new UndergraduateFactory();
		LeiFeng student = factory.CreateLeiFeng();
		
		student.BuyRice();
		student.Sweep();
		student.Wash();
	}

	private static void simpleFactory() {
		LeiFeng studentA = SimpleFactory.CreateLeiFeng("学雷锋的大学生");
		studentA.BuyRice();
		LeiFeng studentB = SimpleFactory.CreateLeiFeng("学雷锋的大学生");
		studentB.Sweep();
		LeiFeng studentC = SimpleFactory.CreateLeiFeng("学雷锋的大学生");
		studentC.Wash();
	}

}

class LeiFeng {
	public void Sweep() {
		System.out.println("sweep the floor");
	}
	
	public void Wash() {
		System.out.println("wash clothes");
	}
	
	public void BuyRice() {
		System.out.println("buy rice");
	}
}

class Undergraduate extends LeiFeng {}

class Volunteer extends LeiFeng {}

class SimpleFactory {
	public static LeiFeng CreateLeiFeng(String type) {
		LeiFeng result = null;
		switch (type) {
		case "学雷锋的大学生":
			result = new Undergraduate();
			break;
		case "社区志愿者":
			result = new Volunteer();
			break;
		}
		return result;
	}
}

interface IFactory {
	LeiFeng CreateLeiFeng();
}

class UndergraduateFactory implements IFactory {

	@Override
	public LeiFeng CreateLeiFeng() {
		return new Undergraduate();
	}
}

class VolueteerFactory implements IFactory {

	@Override
	public LeiFeng CreateLeiFeng() {
		return new Volunteer();
	}
}