学习笔记----------abstractfactory抽象工厂

 

 

一般产生多个实例

 

 

模拟代码:

abstractfactory.java

package abstractfactory; public abstract class AbstractFactory { public abstract Vehicle createVehicle(); public abstract Weapon createWeapon(); public abstract Food createFood(); }  

 

 

DefaultFactory.java     实现AbstractFactory接口

package 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.java        实现AbstractFactory接口

package 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(); } }  

 

 

Food.java

package abstractfactory; public abstract class Food { public abstract void printName(); }  

 

 

Vehicle.java

package abstractfactory; public abstract class Vehicle { public abstract void run(); }  

 

 

Weapon.java

package abstractfactory; public abstract class Weapon { public abstract void shoot(); }  

 

 

Apple.java

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

 

 

Car.java

package abstractfactory; public class Car extends Vehicle { public void run() { System.out.println("ð���̱�����car......."); } }  

AK47.java

package abstractfactory; public class AK47 extends Weapon{ public void shoot() { System.out.println("������..."); } }  

Test.java       这里DefaultFactory f = new DefaultFactory();中的new DefaultFactory();换成new MagicFactory()就可以换掉一套的行为v.run();,w.shoot();,a.printName();,   new MagicFactory()为自定义的(你自己仿照DefaultFactory工厂写吧)

package abstractfactory; public class Test { public static void main(String[] args) { //DefaultFactory f = new DefaultFactory(); AbstractFactory f = new DefaultFactory(); Vehicle v = f.createVehicle(); v.run(); Weapon w = f.createWeapon(); w.shoot(); Food a = f.createFood(); a.printName(); } }  

 

你可能感兴趣的:(apple,String,Class)