****以工厂1和工厂2生产电脑和手机为例**
工厂1和工厂2就是产品族,手机和电脑是产品等级结构**
/抽象的工厂,生产不同的产品等级,具体实现由子工厂实现
public interface IFactory {
Iphone makePhone();
IComputer makeComputer();
}
产品等级接口
//产品等级接口
public interface Iphone {
void phone();
}
public interface IComputer {
void computer();
}
2个产品族,生产各自的产品
public class FactoryOne implements IFactory{
@Override
public Iphone makePhone() {
return new FactoryOnePhone();
}
@Override
public IComputer makeComputer() {
return new FactoryOneComputer();
}
}
public class FactoryTwo implements IFactory {
@Override
public Iphone makePhone() {
return new FactoryTwoPhone();
}
@Override
public IComputer makeComputer() {
return new FactoryTwoComputer();
}
}
具体的产品对象
public class FactoryOnePhone implements Iphone {
@Override
public void phone() {
System.out.println("工厂1的电话");
}
}
public class FactoryOneComputer implements IComputer {
@Override
public void computer() {
System.out.println("工厂1的电脑");
}
}
public class FactoryTwoPhone implements Iphone {
@Override
public void phone() {
System.out.println("工厂2的电话");
}
}
public class FactoryTwoComputer implements IComputer {
@Override
public void computer() {
System.out.println("工厂2的电脑");
}
}
public class Client {
public static void main(String[] args) {
FactoryOne factoryOne = new FactoryOne();
FactoryTwo factoryTwo = new FactoryTwo();
factoryOne.makeComputer().computer();
factoryOne.makePhone().phone();
factoryTwo.makeComputer().computer();
factoryTwo.makePhone().phone();
}
}
工厂1的电脑
工厂1的电话
工厂2的电脑
工厂2的电话