设计模式之工厂模式
简单工厂模式
优点是实现简单,缺点是当需要增加新的产品的时候需要修改工厂代码,违背开闭原则。
1、创建一个接口
public interface Ball { void play(); }
2、具体产品
public class BasketBall implements Ball { @Override public void play() { System.out.println("打篮球"); } }
public class FootBall implements Ball { @Override public void play() { System.out.println("踢足球"); } }
3、工厂
public class BallFactory { public Ball getBall(String type) { if (null == type) { return null; } switch (type) { case "basketball": return new BasketBall(); case "football": return new FootBall(); default: return null; } } }
4、测试
public class Test_ { public static void main(String[] args) { BallFactory ballFactory = new BallFactory(); ballFactory.getBall("basketball").play(); ballFactory.getBall("football").play(); } }
工厂方法模式
解决了简单工厂模式新增产品需要修改工厂的问题,只需要新增具体工厂实现即可。缺点是需要客户端自己选择工厂。
1、产品抽象
public interface Ball { void play(); }
2、具体产品
public class BasketBall implements Ball { @Override public void play() { System.out.println("打篮球"); } }
public class FootBall implements Ball { @Override public void play() { System.out.println("踢足球"); } }
3、工厂抽象
public interface BallFactory { Ball create(); }
4、具体工厂
public class BasketBallFactory implements BallFactory{ @Override public Ball create() { return new BasketBall(); } }
public class FootBallFactory implements BallFactory { @Override public Ball create() { return new FootBall(); } }
5、测试
public class Test_ { public static void main(String[] args) { BallFactory bb = new BasketBallFactory(); BallFactory fb = new FootBallFactory(); bb.create().play(); fb.create().play(); } }