工厂模式最终可以完成
1.任意定制交通工具
2.任意定制生产过程 -- 工厂方法实现
3.任意定制产品一族 -- 抽象工厂实现
抽象工厂(Abstract Factory):提供一个创建产品族的接口,其每个子类可以生产一系列相关产品
例如:
现代人: 开 现代 car -用着热武器 AK47 吃着 面包
魔法人: 骑着扫把 broom ,用着魔法棒 magicstick 吃着蘑菇 mushroom
。。。。。。
定义Food、Vehicle、Weapon
/** * 定义食物 */ public abstract class Food { abstract void printName(); } /** * 定义工具 */ public abstract class Vehicle { abstract void printName(); } /** * 定义武器 */ public abstract class Weapon { abstract void printName(); } ------------------对应武器子类 public class Ak47 extends Weapon { @Override void printName() { System.out.println("ak47..."); } } public class MagicStick extends Weapon { @Override void printName() { System.out.println("magicstic..."); } } ------------------对应食物子类 public class Bread extends Food { @Override void printName() { System.out.println("bread..."); } } public class Mushroom extends Food { @Override void printName() { System.out.println("mushroom..."); } } ------------------对应工具子类 public class Car extends Vehicle { @Override void printName() { System.out.println("car..."); } } public class Broom extends Vehicle { @Override void printName() { System.out.println("broom..."); } }
定义抽象工厂
/** * 定义一个抽象工厂 */ public abstract class AbastractFactory { abstract Food createFood(); abstract Vehicle createVehicle(); abstract Weapon createWeapon(); } public class ModernFactory extends AbastractFactory { @Override Food createFood() { return new Bread(); } @Override Vehicle createVehicle() { return new Car(); } @Override Weapon createWeapon() { return new Ak47(); } } public class MagicFactory extends AbastractFactory { @Override Food createFood() { return new Mushroom(); } @Override Vehicle createVehicle() { return new Broom(); } @Override Weapon createWeapon() { return new MagicStick(); } }
Main方法
public class Main { public static void main(String[] args) { AbastractFactory factory = new ModernFactory(); Food food = factory.createFood(); Vehicle vehicle = factory.createVehicle(); Weapon weapon = factory.createWeapon(); } }
由此可以实现 产品一族的实现