美文网首页
设计模式

设计模式

作者: 孝直 | 来源:发表于2016-08-26 13:38 被阅读0次

    ->工厂方法模式

    //抽象产品角色
    public interface Moveable {  
      void run();
    }
    //具体产品角色
    public class Plane implements Moveable {  
      @Override
        public void run() {  
          System.out.println("plane....");    
      }
    }
    public class Broom implements Moveable {  
      @Override   
     public void run() { 
           System.out.println("broom.....");
        }
    }
    //抽象工厂
    public abstract class VehicleFactory {    
    abstract Moveable create();
    }
    //具体工厂
    public class PlaneFactory extends VehicleFactory{
        public Moveable create() {
            return new Plane();
        }
    }
    public class BroomFactory extends VehicleFactory{
        public Moveable create() {
            return new Broom();
        }
    }
    //测试类public class Test {
        public static void main(String[] args) {
            VehicleFactory factory = new BroomFactory(); 
           Moveable m = factory.create();
            m.run(); 
       }
    }
    

    ->抽象工厂

    //抽象工厂类
    public abstract class AbstractFactory {
      public abstract Vehicle createVehicle();
      public abstract Weapon createWeapon();
      public abstract Food createFood();
    }
    //具体工厂类,其中Food,Vehicle,Weapon是抽象类,
    public class DefaultFactory extends AbstractFactory{
      @Override
      public Food createFood() {
          return new Apple();
      }
      @Override
      public Vehicle createVehicle() {
          return new Car();
      }
      @Override
      public Weapon createWeapon() {
          return new AK47();
      }
    }
    //测试类
    public class Test {
      public static void main(String[] args) {
          AbstractFactory f = new DefaultFactory();
          Vehicle v = f.createVehicle();
          v.run();
          Weapon w = f.createWeapon();
          w.shoot();
          Food a = f.createFood();
          a.printName();
      }
    }
    

    相关文章

      网友评论

          本文标题:设计模式

          本文链接:https://www.haomeiwen.com/subject/zhczsttx.html