public interface IMobilePhone {
public void call();
}
public class NokiaMPhone implements IMobilePhone{
public void call(){
}
}
public class OppoMPhone implements IMobilePhone{
public void call(){
}
}
public interface IFactory {
public IMobilePhone createNokiaPhone();
public IMobilePhone createOppoPhone();
}
public class MobilePhoneFactory implements IFactory{
public IMobilePhone createNokiaPhone(){
return new NokiaMPhone();
}
public IMobilePhone createOppoPhone(){
return new OppoMPhone();
}
}
public class Client {
public static void main(String args[]){
IFactory factory = new MobilePhoneFactory();
IMobilePhone nokia = factory.createNokiaPhone();
IMobilePhone oppo = factory.createOppoPhone();
nokia.call();
oppo.call();
}
}
就代码上而言,工厂模式和抽象工厂模式功能上是差不多的。都通过借口遍程实现了比较好的代码隔离。不同的地方在于factory类的组织。工厂模式对每一个产品均实现一个工厂。而抽象工厂在一个工厂类中建立多个方法返回多种产品。