工厂设计模式(减少耦合。通过接口或者工厂类来实现)

耦合性:粘度强(依耐性) Person p = new Person();  //耦合性强

             Man p = new Person();     //耦合性弱,Man是接口或其它,Person实现这个接口

简单工厂模式是有一个工厂对象决定创建哪一种产品类的实例。

简单工厂模式是工厂模式家族中最简单有用的模式.以下给出演示样例代码:

/**
* 简单工厂设计模式
* @author Admin
*
*/
public class FactoryDesign { public static void main(String[] args) {
Car car1 = Factory.getCar("small"); //通过接口来接收对象减少依赖度(耦合性)
Car car2 = Factory.getCar("big");
if(car1!=null){
car1.run();
}
if(car2!=null){
car2.run();
}
} } class Factory{ //工厂类,来间接控制生产对象
public static Car getCar(String name){
if(name.equals("small")){
return new smallCar(); //生产小汽车
}else if(name.equals("big")){
return new bigCar(); // 生产大汽车
}else return null;
}
} interface Car{
public void run();
}
class smallCar implements Car{
@Override
public void run() {
System.out.println("小汽车在跑");
}
}
class bigCar implements Car{
@Override
public void run() {
System.out.println("大汽车在跑");
}
}

实验结果:

最新文章

  1. 使用VS2015进行C++开发的6个主要原因
  2. 【.net core 跨平台】第一步 在Ubuntu16.04 配置.net core环境
  3. jQuery代码节选(筛选)
  4. IOS OC 多任务定时器 NSRunLoop 管理 NSTimer
  5. Android开发LogCat一直不停输出的解决方法
  6. const实现
  7. C# 语音识别
  8. 通过SQL Server Profiler来监视分析死锁
  9. How to setup ELM327 Bluetooth WiFi for Android software Torque
  10. nginx rewrite 参数和例子
  11. empty函数PHP
  12. oracle常见为题汇总,以及一个简单数据连接操作工厂
  13. struts2笔记06-ServletXxxAware接口
  14. 使用 jackson序列格式化日期
  15. asp代码写的,微信会员报名转发分享带上下级和邀约人关系并且能微信支付asp编号的
  16. Python学习心得--变量类型篇
  17. linux ubuntu 学习总结(day01)基本命令学习
  18. sourcetree的安装及使用
  19. 160301、js倒计时,页面上显示时间
  20. redis rdb文件解析

热门文章

  1. [BZOJ4542] [JZYZOJ2014][Hnoi2016] 大数(莫队+离散化)
  2. 【欧拉函数】BZOJ4173-数学
  3. Codeforces Beta Round #92 (Div. 1 Only) A. Prime Permutation 暴力
  4. linux基础命令学习(四)用户与群组
  5. 面试&笔试---c语言之字符串处理
  6. undefined null 各种值比较(面试题)
  7. PHP格式化金钱函数
  8. Out of memory: Kill process 内存不足
  9. JS中实现字符串和数组的相互转化
  10. cocos2d-x:将iOS项目编译成Andriod项目