上篇的FactoryMethod阐述的是生产不同的交通工具的工厂,要么让老张单独的开车去,要么让他单独的开飞机去,但是呢,这样老张不是很孤独寂寞去东北吗?一点娱乐的气息都木有,OK,现在我们酝酿一个这样的场景,让老张开着车,叼着苹果,扛着AK47去东北,这样老张就不无聊了,车、苹果、AK47,这是一个系列的产品,而AbstractFactory就是解决系列产品生产问题。
二、AbstractFactory
AbstractFactory模式
除了生产正常世界的系列产品,我们还可以生产魔法世界的系列产品(扫帚、魔法棒等),其实我们用的QQ或者酷我音乐盒等所用的皮肤更换功能,都是AbstractFactory模式的体现。
1 public abstract class Vehicle { 2 public abstract void run(); 3 }
1 public abstract class Weapon { 2 public abstract void shoot(); 3 }
1 public abstract class Food { 2 public abstract void printName(); 3 }
1 public class Car extends Vehicle{ 2 public void run() { 3 System.out.println("car run"); 4 } 5 }
1 public class AK47 extends Weapon{ 2 public void shoot() { 3 System.out.println("AK47 shoot"); 4 } 5 }
1 public class Apple extends Food{ 2 public void printName() { 3 System.out.println("apple"); 4 } 5 }
1 public abstract class AbstractFactory { 2 public abstract Vehicle createVehicle(); 3 public abstract Weapon createWeapon(); 4 public abstract Food createFood(); 5 }
1 public class DefaultFactory extends AbstractFactory{ 2 3 @Override 4 public Car createVehicle() { 5 // TODO Auto-generated method stub 6 return new Car(); 7 } 8 9 @Override 10 public Weapon createWeapon() { 11 // TODO Auto-generated method stub 12 return new AK47(); 13 } 14 15 @Override 16 public Food createFood() { 17 // TODO Auto-generated method stub 18 return new Apple(); 19 } 20 21 }
1 public class Bloom extends Vehicle { 2 3 @Override 4 public void run() { 5 System.out.println("bloom run"); 6 } 7 8 }
1 public class MagicStick extends Weapon { 2 3 @Override 4 public void shoot() { 5 System.out.println("magicstick shoot"); 6 } 7 8 }
1 public class Muslrom extends Food { 2 3 @Override 4 public void printName() { 5 System.out.println("muslrom"); 6 } 7 8 }
1 public class MagicFactory extends AbstractFactory{ 2 3 @Override 4 public Vehicle createVehicle() { 5 // TODO Auto-generated method stub 6 return new Bloom(); 7 } 8 9 @Override 10 public Weapon createWeapon() { 11 // TODO Auto-generated method stub 12 return new MagicStick(); 13 } 14 15 @Override 16 public Food createFood() { 17 // TODO Auto-generated method stub 18 return new Muslrom(); 19 } 20 21 }
1 public class Test { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 AbstractFactory d = new DefaultFactory(); 8 // AbstractFactory d = new MagicFactory(); 9 Vehicle c = d.createVehicle(); 10 c.run(); 11 Weapon ak = d.createWeapon(); 12 ak.shoot(); 13 Food a = d.createFood(); 14 a.printName(); 15 } 16 17 }
这样,我们只需要改变工厂就可改变一系列的产品。
AbstractFactory类结构
由图可知,DefaultFactory和MagicFactory都实现AbstractFactory,DefaultFactory生产Car、AK47、Apple这一系列产品,而MagicFactory生产Broom、MagicStick、Muslroom。