工厂方法模式
工厂方法模式:定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
(简单理解就是比简单工厂模式多了一个抽象工厂,还有各种实例工厂)解决了简单工厂模式违背了开放-封闭原则的缺点
简单工厂模式在上一篇文章:http://www.cnblogs.com/maggiejyt/p/7561152.html
UML图
例子:用工厂模式去实现Ball,比较简单工厂模式
UML图
IFactory:工厂接口
package com.maggie.FactoryMethod; public interface IFactory { public abstract Ball createBall(); }
FootFactory 足球工厂
package com.maggie.FactoryMethod; public class FootFactory implements IFactory { @Override public Ball createBall() { // TODO Auto-generated method stub return new FootBall("white+black"); } }
BasketFactory 篮球工厂
package com.maggie.FactoryMethod; public class BasketFactory implements IFactory { @Override public Ball createBall() { // TODO Auto-generated method stub return new BasketBall("oranger"); } }
Ball 产品的抽象类(或接口)
package com.maggie.FactoryMethod; public abstract class Ball { private String color; public Ball(String color) { super(); this.color = color; } public Ball() { super(); } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public abstract void play(); }
BasketBall 篮球
package com.maggie.FactoryMethod; public class BasketBall extends Ball { @Override public void play() { String player = "the ball's color is "+this.getColor()+",I am BasketBall"; System.out.println(player); } public BasketBall() { super(); // TODO Auto-generated constructor stub } public BasketBall(String color) { super(color); // TODO Auto-generated constructor stub } }
FootBall 足球
package com.maggie.FactoryMethod; public class FootBall extends Ball { @Override public void play() { String player = "the ball's color is "+this.getColor()+",I am FootBall"; System.out.println(player); } public FootBall() { super(); // TODO Auto-generated constructor stub } public FootBall(String color) { super(color); // TODO Auto-generated constructor stub } }
客户端的调用
package com.maggie.FactoryMethod; public class Client { public static void main(String[] args) { IFactory iFactory = null; iFactory = new FootFactory(); Ball footBall = iFactory.createBall(); footBall.play(); iFactory = new BasketFactory(); Ball basketBall = iFactory.createBall(); basketBall.play(); } }
输出
the ball's color is white+black,I am FootBall the ball's color is oranger,I am BasketBall
工厂方法模式跟简单工厂模式的比较:
简单工厂模式把所以品种的产品都在同一个工厂类中生产,则工厂类需要涉及到很多逻辑关系,一旦产品的种类增加,则这个逻辑也就要改变,就要去改变工厂类里面的代码,这样就违背了开放-封闭原则,而工厂模式用一个接口把工厂提取出来每种产品都有自己的工厂类,则增加一种产品就只需增加一个产品的工厂类,就不需要去改变任何类里面的代码,这样就可解决了简单工厂模式违背了开放-封闭原则的缺点。