简单工厂模式和工厂方法模式

1. 简单工厂模式



publci class Sample{
....
}

public class A extends Sample{
....
}

public class B extends Sample{
......
}







工厂类处于决定实例化那个产品类的中心位置





public class Factory{

//静态工厂方法,无必要再去实例化这个工厂类,增加没有必要的代码
public static Sample create(int which){
if(which==1)
return new A();
if(which==2)
return new B();
}
}



使用简单工厂初始化一个类




Sample newSample=Factory.create(1);



2. 工厂方法模式
植物接口及两个实现类





public interface Plant{}

public class PlantA implements Plant{
}

public class PlantB implements Plant{
}




水果接口及两个实现类




public interface Fruit{}

public class FruitA implements Fruit{
}

public class FruitB implements Fruit{
}



抽象工厂





public interface AbstractFactory{
public Plant createPlant();
public Fruit creatFruit();
}




工厂类A




public Class FactoryA implements AbstractFactory{
public Plant createPlant(){
return new PlantA();
}
public Fruit creatFruit(){
return new FruitA();
}
}



工厂类B





public Class FactoryB implements AbstractFactory{
public Plant createPlant(){
return new PlantB();
}
public Fruit creatFruit(){
return new FruitB();
}
}



工厂方法模式与简单工厂模式再结构上的不同不是很明显。工厂方法类的核心是一个抽象工厂类,而简单工厂模式把核心放在一个具体类上。

  工厂方法模式之所以有一个别名叫多态性工厂模式是因为具体工厂类都有共同的接口,或者有共同的抽象父类。

  当系统扩展需要添加新的产品对象时,仅仅需要添加一个具体对象以及一个具体工厂对象,原有工厂对象不需要进行任何修改,也不需要修改客户端,很好的符合了"开放-封闭"原则。而简单工厂模式在添加新产品对象后不得不修改工厂方法,扩展性不好。

  工厂方法模式退化后可以演变成简单工厂模式。

新增加一个类PlantC 和 FruitC




public class PlantC implements Plant{
}
public class FruitC implements Fruit{
}



这时只需要增加一个工厂类C



public Class FactoryC implements AbstractFactory{
public Plant createPlant(){
return new PlantC();
}
public Fruit creatFruit(){
return new FruitC();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值