[Factory Method]:Source Sample
来源:互联网 发布:网络管理软件下载 编辑:程序博客网 时间:2024/06/06 21:43
代码:
package factoryMethod;
//定义水果接口
interface Fruit {
void plant(); //水果是被种植的
void enableEat();//水果能吃
}
//苹果类实现水果接口
class Apple implements Fruit {
public void plant() {
System.out.println("Plant apple");
}
public void enableEat() {
System.out.println("Eat apple");
}
}
//葡萄类实现水果接口
class Grape implements Fruit {
public void plant() {
System.out.println("Plant grape");
}
public void enableEat() {
System.out.println("Eat grape");
}
}
//鸭梨类实现水果接口
class Pear implements Fruit {
public void plant() {
System.out.println("Plant pear");
}
public void enableEat() {
System.out.println("Eat pear");
}
}
//新增加了桔子类,同样实现水果接口
class Orange implements Fruit {
public void plant() {
System.out.println("Plant orange");
}
public void enableEat() {
System.out.println("Eat orange");
}
}
//将买水果类定义为接口类
interface BuyFruit {
//定义买水果这个过程
public Fruit buyFruit();
}
//买苹果实现了买水果这个接口
class BuyApple implements BuyFruit {
public Fruit buyFruit() {
return new Apple();
}
}
//买葡萄实现了买水果这个接口
class BuyGrape implements BuyFruit {
public Fruit buyFruit() {
return new Grape();
}
}
//买鸭梨实现了买水果这个接口
class BuyPear implements BuyFruit {
public Fruit buyFruit() {
return new Pear();
}
}
//新增加的买桔子,同样实现了买水果这个接口
class BuyOrange implements BuyFruit {
public Fruit buyFruit() {
return new Orange();
}
}
public class FactoryMethod {
public static void main(String[] args) {
BuyApple buy = new BuyApple();
BuyGrape buy2 = new BuyGrape();
buy.buyFruit().enableEat();
buy2.buyFruit().enableEat();
//新增加的买桔子这个动作可以直接使用了
BuyOrange buy3 = new BuyOrange();
buy3.buyFruit().plant();
buy3.buyFruit().enableEat();
}
}
说明:
A:工厂方法模式和简单工厂模式在结构上的不同是很明显的。工厂方法模式的核心是一个抽象工厂类,而简单工厂模式把核心放在一个具体类上。工厂方法模式可以允许很多具体工厂类从抽象工厂类中将创建行为继承下来,从而可以成为多个简单工厂模式的综合,进而推广了简单工厂模式。
B:工厂方法模式退化后可以变得很像简单工厂模式。设想如果非常确定一个系统只需要一个具体工厂类,那么就不妨把抽象工厂类合并到具体的工厂类中去。由于反正只有一个具体工厂类,所以不妨将工厂方法改成为静态方法,这时候就得到了简单工厂模式。C:如果需要加入一个新的水果,那么只需要加入一个新的水果类以及它所对应的工厂类。没有必要修改客户端,也没有必要修改抽象工厂角色或者其他已有的具体工厂角色。对于增加新的水果类而言,这个系统完全支持“开-闭”原则。
D:对Factory Method模式而言,它只是针对一种类别(如本例中的水果类Fruit),但如果我们还想买肉,那就不行了,这是就必须要Abstract Factory Method模式帮忙了。
- [Factory Method]:Source Sample
- [Simple Factory]:Source Sample
- Factory Method
- factory method
- Factory Method
- Factory Method
- Factory Method
- Factory Method
- Factory Method
- Factory Method
- Factory Method
- Factory Method
- Factory Method
- Factory Method
- Factory Method
- Factory Method
- Factory Method
- factory method
- 我的2005年
- 修改ACCESS数据库字段属性
- 读petshop3.0--多层应用架构(z)
- 两段经典的图片验证码程序之二
- 关于打印系列之一
- [Factory Method]:Source Sample
- C#操作XML
- 两段经典的图片验证码程序之一
- [php生成无限级select]用正则遍历数组生成,只查两次数据库
- ActiveX控件的MFC设计之旅-第3步
- Java用户界面本地化实例讲解
- 用VB操作INI文件
- Solaris Server 設定方法
- 八皇后问题程序