标签:
一、工厂方法模式
简单工厂模式的缺陷就是类的创建太过于依赖工厂,一旦需要进行程序扩展,就必须修改工厂类的代码
这违背了背包原则。而工厂方法模式针对这一问题进行了改进。
public interface Sender { public void send(); } public interface producer { public Sender produce(); } public class MailFactory implements producer{ public Sender produce() { return new Mail(); } } public class Mail implements Sender{ public void send() { System.out.println("mail is sending "); } } //测试类 public class FactoryPatten { public static void main(String[] args) { MailFactory mailFactory = new MailFactory(); Sender sender = mailFactory.produce(); sender.send(); } }
二、抽象工厂模式
工厂方法模式和抽象工厂模式不好分清楚
工厂方法模式:
一个抽象产品类,可以派生出很多具体产品类
一个抽象工厂类,可以派生出很多具体工厂类
每一个具体工厂类只能创建一个具体产品的实例
抽象工厂模式:
多个抽象产品类,每个抽象产品类可以派生出多个具体产品类。
一个抽象工厂类,可以派生出多个具体工厂类。
每个具体工厂类可以创建多个具体产品类的实例,也就是创建的是一个产品线下的多个产品。
package day03; interface ProduceComputer{}//抽象电脑产品 interface ProduceHouse{}//抽象家用,以下只用抽象电脑产品举例 interface Factory{}//抽象工厂 //A工厂的鼠标 class MouseA implements ProduceComputer{ MouseA(){ System.out.println("MouseA has created"); } public void doSomething(){ System.out.println("MouseA is running"); } } //B工厂的鼠标 class MouseB implements ProduceComputer{ MouseB(){ System.out.println("MouseB has created"); } public void doSomething(){ System.out.println("MouseB is running"); } } //A工厂的键盘 class keyBoardA implements ProduceComputer{ keyBoardA(){ System.out.println("keyBoardA has created"); } public void doSomething(){ System.out.println("keyBoardA is running"); } } //B工厂的键盘 class keyBoardB implements ProduceComputer{ keyBoardB(){ System.out.println("keyBoardB has created"); } public void doSomething(){ System.out.println("keyBoardB is running"); } } //A工厂,生产A工厂的产品 class FactoryA implements Factory{ public MouseA produceMouseA(){ return new MouseA(); } public keyBoardA produceKeyBoardA(){ return new keyBoardA(); } } //B工厂,生产B工厂的产品 class FactoryB implements Factory{ public MouseB produceMouseB(){ return new MouseB(); } public keyBoardB produceKeyBoardB(){ return new keyBoardB(); } } //测试类 public class AbstractFactory { public static void main(String[] args) { MouseA ma = new FactoryA().produceMouseA(); ma.doSomething(); keyBoardA ka = new FactoryA().produceKeyBoardA(); ka.doSomething(); MouseB mb = new FactoryB().produceMouseB(); mb.doSomething(); keyBoardB kb = new FactoryB().produceKeyBoardB(); kb.doSomething(); } }
标签:
原文地址:http://blog.csdn.net/wjw0130/article/details/42049593