简单工厂模式
来源:互联网 发布:新东方网络课下载 编辑:程序博客网 时间:2024/06/02 07:07
从这节开始学习设计模式,首先学习创建模式,其中工厂模式是创建模式里面最常见也常用的一种,工厂模式又分简单工厂模式(Simple Factory),工厂方法模式(Factory Method)和抽象工厂模式(Abstractor Factory),这里先学习最简单的也就是简单工厂模式。
简单工厂模式(Simple Factory)也称静态工厂方法模式,是工厂方法模式的特殊实现。简单工厂模式的一般性结构如下图:
工厂根据传入的参数来创建具体车的类型。上图中无法形象地表示抽象类所以用接口代替了。
java代码如下:
- package
com.pattern.SimpleFactory; -
- public
class Factory { -
-
public TrafficMachine creator(String type) throws TypeErrorException{ -
if(type.equals("Automobile")){ -
return new Automobile(); -
}else if (type.equals("Tractor")) { -
return new Tractor(); -
}else if (type.equals("Train")) { -
return new Train(); -
}else{ -
throw new TypeErrorException("not find +type);" -
} -
} - }
- package
com.pattern.SimpleFactory; -
- public
class Automobile extends TrafficMachine{ - @Override
- public
void traffic() { - //
TODO Auto-generated method stub - }
- }
- package
com.pattern.SimpleFactory; -
- public
class Tractor extends TrafficMachine{ - @Override
- public
void traffic() { - //
TODO Auto-generated method stub - }
-
- public
void plough(){ - }
- }
- package
com.pattern.SimpleFactory; -
- public
class Train extends TrafficMachine { - private
int nodeNum; //节数 - private
int trainNum; //车次 - @Override
- public
void traffic() { - //
TODO Auto-generated method stub - }
- public
int getNodeNum() { - return
nodeNum; - }
- public
void setNodeNum(int nodeNum) { - this.nodeNum
= nodeNum; - }
- public
int getTrainNum() { - return
trainNum; - }
- public
void setTrainNum(int trainNum) { - this.trainNum
= trainNum; - }
- }
- package
com.pattern.SimpleFactory; -
- public
abstract class TrafficMachine { - public
float power ; - public
float load ; - public
abstract void traffic(); - }
- package
com.pattern.SimpleFactory; -
- public
class TypeErrorException extends Exception{ -
- private
static final long serialVersionUID = 562037380358960152L; - public
TypeErrorException(String message) { - super(message);
- //
TODO Auto-generated constructor stub - }
- }
简单工厂的优缺点:
- 工厂模式-简单工厂
- 工厂模式-简单工厂
- 工厂模式-简单工厂模式
- 工厂模式-简单工厂模式
- 简单工厂模式,工厂模式
- 工厂模式-简单工厂模式
- 简单工厂模式,工厂模式
- 简单工厂、工厂模式、抽象工厂模式
- 简单工厂、工厂模式、抽象工厂模式
- 简单工厂&工厂模式&抽象工厂模式
- 简单工厂和工厂模式
- 简单工厂和工厂模式
- 1,工厂模式--简单工厂
- 简单工厂和工厂模式
- 简单工厂,工厂模式,抽象工厂
- 简单工厂,工厂模式,抽象工厂
- 简单工厂、工厂方法、抽象工厂模式
- 简单工厂、工厂模式和抽象工厂
- Java CyclicBarrier
- Linux忘记 root密码的解决办法
- 浏览器使用技巧杂记
- FIFO核的使用
- Android 使用TCPdump工具,抓TCP数据包。
- 简单工厂模式
- 如何应用Xfermode
- (四)Android百度公交开发—百度地图API之根据经纬度查询地址信息
- struts1.2中ActionForm和ServletFileUpload.parseReq...
- linux lsof命令详解
- hadoop、大数据面试题
- Install Oracle Java JDK 1.8 On CentOS 6.5
- nginx转发apache
- 关于checkbox的全选问题