设计模式--工厂方法模式
工厂方法模式是在简单工厂模式上都优化,不用再去写Factoty 接口,新建一个appleFactory 即可, 实现开放(可以扩展)封闭(不需要再去改原先都代码)原则:
具体看代码:
基类:
public interface Fruit {
/*
* 采集
*/
public void get();
}
共同接口
package FactoryMethod;
/**
* 类说明
*
* <pre>
* Modify Information:
* Author Date Description
* ============ =========== ============================
* DELL 2017年2月7日 Create this file
* </pre>
*
*/
public interface FruitFactory {
public Fruit getFruit();
}
实现香蕉工厂
package FactoryMethod;
/**
* 类说明
*
* <pre>
* Modify Information:
* Author Date Description
* ============ =========== ============================
* DELL 2017年2月7日 Create this file
* </pre>
*
*/
public class BananaFactory implements FruitFactory{
/**
* @see FactoryMethod.FruitFactory#getFruit()
*/
@Override
public Fruit getFruit() {
return (Fruit) new Banana();
}
}
package FactoryMethod;
/**
* 类说明
*
* <pre>
* Modify Information:
* Author Date Description
* ============ =========== ============================
* DELL 2017年2月7日 Create this file
* </pre>
*
*/
public class Banana implements Fruit{
/**
* @see FactoryMethod.Fruit#get()
*/
@Override
public void get() {
System.out.println("采集香蕉");
}
}
同理香蕉 梨 都一样:
package FactoryMethod;
/**
* 类说明
*
* <pre>
* Modify Information:
* Author Date Description
* ============ =========== ============================
* DELL 2017年2月7日 Create this file
* </pre>
*
*/
public class AppleFactory implements FruitFactory {
/**
* @see FactoryMethod.FruitFactory#getFruit()
*/
@Override
public Fruit getFruit() {
return (Fruit) new Apple();
}
}
package FactoryMethod;
/**
* 类说明
*
* <pre>
* Modify Information:
* Author Date Description
* ============ =========== ============================
* DELL 2017年2月7日 Create this file
* </pre>
*
*/
public class Apple implements Fruit{
/*
* 实现开放封闭,创建产品都工厂接口,将实际工作放到子类中
*/
public void get(){
System.out.println("采集苹果");
}
}
测试类:
public class MainClass {
public static void main(String[] args) {
//获得AppleFactory
FruitFactory ff = new AppleFactory();
//通过AppleFactory来获得Apple实例对象
Fruit apple = ff.getFruit();
apple.get();
//获得BananaFactory
FruitFactory ff2 = new BananaFactory();
Fruit banana = ff2.getFruit();
banana.get();
//获得PearFactory
FruitFactory ff3 = new PearFactory();
Fruit pear = ff3.getFruit();
pear.get();
}
}