以商店烤面包的例子谈一下简单工厂模式与工厂方法模式:
使用继承和多态将面包分离,修改或增加某种面包不会影响其他面包烘烤,。
package factory_Method;
//将各种不同的面包分离,修改或增加某种面包不会影响其他面包的烘焙
public abstract class BreadMaker {
public abstract void GetBread();
}
package factory_Method;
public class HoneyBread extends BreadMaker{
@Override
public void GetBread() {
// TODO Auto-generated method stub
System.out.println("烤出了蜜蜂面包");
}
}
public class BlackBread extends BreadMaker
{
@Override
public void GetBread() {
System.out.println("烤出了黑面包");
}
}
public class WhiteBread extends BreadMaker{
@Override
public void GetBread() {
// TODO Auto-generated method stub
System.out.print("烤出了白面包");
}
}
一、简单工厂模式实现:
package factory_Method;
public class SimpleBreadFactory {
public static BreadMaker MakeBread(int breadType){
BreadMaker breadMaker = null;
switch (breadType) {
case 1:
breadMaker = new BlackBread();
break;
case 2:
breadMaker = new HoneyBread();
break;
case 3:
breadMaker = new WhiteBread();
default:
break;
}
return breadMaker;
}
public static void main(String[] args) {
BreadMaker breadMaker;
System.out.println("顾客要黑面包:");
breadMaker=SimpleBreadFactory.MakeBread(1);
breadMaker.GetBread();
System.out.println("顾客要蜜蜂面包:");
breadMaker=SimpleBreadFactory.MakeBread(2);
breadMaker.GetBread();
System.out.println("顾客要白面包:");
breadMaker=SimpleBreadFactory.MakeBread(3);
breadMaker.GetBread();
}
}
只要输入想要的面包代码,面包工厂就会实例化合适的对象,通过多态来返回父类实例的方式实现给出不同面包的目的。当需要增加新面包种类时,只需增加后台面包类和修改简单面包工厂类Case,给维护带了方便。
二、工厂方法模式
修改简单面包工厂类破坏了设计原则——开放-封闭原则,特别是种类特别多时。为了扩展方便又修改关闭。引出简单工厂的升级版——工厂方法模式。
下面说下定义
工厂方法模式的定义:“顶一个一个用户创建对象的接口,让子类决定实例化哪个类。工厂方法使一个类的实例化延迟到其子类”。
改进如下:
1.给出工厂接口的定义:
package factory_Method;
//接口工厂
public interface IBreadFactoryMethod {
BreadMaker CreateBread();
}
2.不同的面包建立一个具体工厂方法来实现这个接口
package factory_Method;
public class BlackBreadFactory implements IBreadFactoryMethod {
@Override
public BreadMaker CreateBread() {
// TODO Auto-generated method stub
return new BlackBread();
}
}
public class HoneyBreadFactory implements IBreadFactoryMethod {
@Override
public BreadMaker CreateBread() {
// TODO Auto-generated method stub
return new HoneyBread();
}
}
public class WhiteBreadFactory implements IBreadFactoryMethod {
@Override
public BreadMaker CreateBread() {
// TODO Auto-generated method stub
return new WhiteBread();
}
}
客户端代码实现:
package factory_Method;
public class BreadFactoryMethod{
public static void main(String[] args) {
BreadMaker breadMaker;
//顾客要黑面包
System.out.println("顾客要黑面包:");
//根据需要实例化接口
IBreadFactoryMethod breadFactoryMethod = new BlackBreadFactory();
breadMaker = breadFactoryMethod.CreateBread();
breadMaker.GetBread();
//顾客要蜜蜂面包
System.out.println("顾客要蜜蜂面包:");
breadFactoryMethod = new HoneyBreadFactory();
breadMaker = breadFactoryMethod.CreateBread();
breadMaker.GetBread();
//顾客要白面包
System.out.println("顾客要白面包:");
breadFactoryMethod = new WhiteBreadFactory();
breadMaker = breadFactoryMethod.CreateBread();
breadMaker.GetBread();
}
}
这样一来,新代码中如果增加新的面包种类,只需增加新的面包类和新的工厂接口的实现就OK了,而将具体实例化哪个类在客户端判断就行。