设计模式------工厂方法(Factory Method)


定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法模式有四个要素:产品接口,产品实现,工厂接口,工厂实现。

以下是个典型工厂方法的例子

interface IProduct {  
    public void productMethod();  
}  
  
class Product implements IProduct {  
    public void productMethod() {  
        System.out.println("产品");  
    }  
}  
  
interface IFactory {  
    public IProduct createProduct();  
}  
  
class Factory implements IFactory {  
    public IProduct createProduct() {  
        return new Product();  
    }  
}  
  
public class Client {  
    public static void main(String[] args) {  
        IFactory factory = new Factory();  
        IProduct prodect = factory.createProduct();  
        prodect.productMethod();  
    }  
}  


典型应用例子:

场景:汽车由发动机、轮、底盘组成,现在需要组装一辆车交给调用者。假如不使用工厂模式,代码如下:

class Engine {  
    public void getStyle(){  
        System.out.println("这是汽车的发动机");  
    }  
}  
class Underpan {  
    public void getStyle(){  
        System.out.println("这是汽车的底盘");  
    }  
}  
class Wheel {  
    public void getStyle(){  
        System.out.println("这是汽车的轮胎");  
    }  
}  
public class Client {  
    public static void main(String[] args) {  
        Engine engine = new Engine();  
        Underpan underpan = new Underpan();  
        Wheel wheel = new Wheel();  
        ICar car = new Car(underpan, wheel, engine);  
        car.show();  
    }  
}  
调用者为了组装汽车还需要另外实例化发动机、底盘和轮胎,而这些汽车的组件是与调用者无关的,严重违反了迪米特法则,耦合度太高。并且非常不利于扩展

假如使用工厂方法的话,整个架构就显得清晰了许多:

interface IFactory {  
    public ICar createCar();  
}  
class Factory implements IFactory {  
    public ICar createCar() {  
        Engine engine = new Engine();  
        Underpan underpan = new Underpan();  
        Wheel wheel = new Wheel();  
        ICar car = new Car(underpan, wheel, engine);  
        return car;  
    }  
}  
public class Client {  
    public static void main(String[] args) {  
        IFactory factory = new Factory();  
        ICar car = factory.createCar();  
        car.show();  
    }  
}  
使用工厂方法后,调用端的耦合度大大降低了。并且对于工厂来说,是可以扩展的,以后如果想组装其他的汽车,只需要再增加一个工厂类的实现就可以




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值