• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
gaohuan30
博客园    首页    新随笔    联系   管理    订阅  订阅
工厂方法(Factory Method)

  工厂模式最终可以完成  

    1.任意定制交通工具

    2.任意定制生产过程 -- 工厂方法实现

    3.任意定制产品一族  -- 抽象工厂实现

 

  工厂方法-(Factory Method) : 定义一个用于创建产品的接口,由子类决定生产什么产品

/**
 * 定义一个交通工具
 */
public interface Vehicle {
    void go();
}
/**
 * 飞行扫把
 */
public class Broom implements Vehicle {
    @Override
    public void go() {
        System.out.println("broom go");
    }
}
/**
 * 汽车
 */
public class Car implements Vehicle {
    @Override
    public void go() {
        System.out.println("car go");
    }
}
/**
 * 飞机
 */
public class Plane implements Vehicle {
    @Override
    public void go() {
        System.out.println("plane go ");
    }
}

  

/**
 * 交通创建工厂
 */
public interface VehicleFactory {
    Vehicle create();
}
public class BroomFactory implements VehicleFactory {
    @Override
    public Vehicle create() {
        System.out.println(" create broom before");
        return new Broom();
    }
}
public class CarFactory implements VehicleFactory {
    @Override
    public Vehicle create() {
        System.out.println(" create car before");
        return new Car();
    }
}
public class PlaneFactory implements VehicleFactory {
    @Override
    public Vehicle create() {
        System.out.println(" create plane before");
        return new Plane();
    }
}

 

public class Main {
    public static void main(String[] args) {
        Vehicle car = new CarFactory().create();
        car.go();
        Vehicle plane = new PlaneFactory().create();
        plane.go();
    }
}


结果: create car before car go create plane before plane go

  

posted on 2020-04-19 19:13  gaohuan30  阅读(204)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3