[Java] 设计模式之工厂系列 02-面向抽象编程 抽象工厂 - 缺点 : 产生新的产品品种的时候,改动太多

 (1), JDK 中 factory 也是比比皆是。 (2), 抽象工厂 -- 换皮肤的软件

Vehicle

package com.bjsxt.dp.factory.abstractfactory;

public abstract class Vehicle {
	public abstract void run();
}
Weapon
package com.bjsxt.dp.factory.abstractfactory;

public abstract class Weapon {
	public abstract void shoot();
}
Food
package com.bjsxt.dp.factory.abstractfactory;

public abstract class Food {
	public abstract void printName();
}
AbstractFactory
package com.bjsxt.dp.factory.abstractfactory;

public abstract class AbstractFactory {
	public abstract Vehicle createVehicle();
	public abstract Weapon createWeapon();
	public abstract Food createFood();
	
}
Carextends Vehicle
package com.bjsxt.dp.factory.abstractfactory;


public class Car extends Vehicle {
	
	public void run() {
		System.out.println("冒着烟奔跑中car.......");
	}
}
 Broom  extends Vehicle
package com.bjsxt.dp.factory.abstractfactory;

public class Broom  extends Vehicle {

	public void run() {
		System.out.println("一路沙尘暴飞奔而来broom.....");
	}

}
AK47 extends Weapon
package com.bjsxt.dp.factory.abstractfactory;

public class AK47 extends Weapon {
	public void shoot() {
		System.out.println("哒哒哒...");
	}
}
MagicStick extends Weapon
package com.bjsxt.dp.factory.abstractfactory;

public class MagicStick extends Weapon {

	@Override
	public void shoot() {
		System.out.println("fire hu hu hu ...");
	}

}
Apple extends Food
package com.bjsxt.dp.factory.abstractfactory;

public class Apple extends Food {
	public void printName() {
		System.out.println("apple");
	}
}
MushRoom extends Food
package com.bjsxt.dp.factory.abstractfactory;

public class MushRoom extends Food {

	@Override
	public void printName() {
		// TODO Auto-generated method stub
		System.out.println("mushroom");
	}

}
DefaultFactory extends AbstractFactory
package com.bjsxt.dp.factory.abstractfactory;

public class DefaultFactory extends AbstractFactory {

	@Override
	public Food createFood() {
		// TODO Auto-generated method stub
		return new Apple();
	}

	@Override
	public Vehicle createVehicle() {
		// TODO Auto-generated method stub
		return new Car();
	}

	@Override
	public Weapon createWeapon() {
		// TODO Auto-generated method stub
		return new AK47();
	}

}
MagicFactory extends AbstractFactory

package com.bjsxt.dp.factory.abstractfactory;

public class MagicFactory extends AbstractFactory {

	@Override
	public Food createFood() {
		// TODO Auto-generated method stub
		return new MushRoom();
	}

	@Override
	public Vehicle createVehicle() {
		// TODO Auto-generated method stub
		return new Broom();
	}

	@Override
	public Weapon createWeapon() {
		// TODO Auto-generated method stub
		return new MagicStick();
	}
	
}

 抽象工厂针对是产品系列, 工厂方法则只是在子类中实例化对象,能控制生产过程。
posted @ 2014-01-26 13:29  小尼人00  阅读(129)  评论(0编辑  收藏  举报