/**
* 抽象工厂
*/
public abstract class AbstractFactory {
protected abstract Computer getComputer();
public Computer getComputer(String name) {
if (name.equals("Dell")) {
return new DellFactory().getComputer();
} else if (name.equals("MacBook")) {
return new MacBookFactory().getComputer();
} else if (name.equals("HP")) {
return new HPFactory().getComputer();
} else {
System.out.println("制造不出该品牌电脑");
return null;
}
}
}
/**
* 戴尔的工厂
*/
public class DellFactory extends AbstractFactory {
@Override
protected Computer getComputer() {
return new Dell();
}
}
/**
* 戴尔电脑
*/
public class Dell implements Computer {
@Override
public String getName() {
return "Dell";
}
}
/**
* 惠普的工厂
*/
public class HPFactory extends AbstractFactory {
@Override
protected Computer getComputer() {
return new HP();
}
}
/**
* 惠普电脑
*/
public class HP implements Computer {
@Override
public String getName() {
return "HP";
}
}
/**
* 苹果的工厂
*/
public class MacBookFactory extends AbstractFactory {
@Override
protected Computer getComputer() {
return new MacBook();
}
}
/**
* 苹果电脑
*/
public class MacBook implements Computer {
@Override
public String getName() {
return "MacBook";
}
}
/**
* 默认工厂:默认生产 Dell
*/
public class DefaultFactory extends AbstractFactory {
private DellFactory defaultFactory = new DellFactory();
@Override
protected Computer getComputer() {
return defaultFactory.getComputer();
}
}
/**
* 测试
*/
public class Test {
public static void main(String[] args) {
Computer computer = new DefaultFactory().getComputer("HP");
System.out.println(computer.getName());
computer=new DefaultFactory().getComputer();
System.out.println(computer.getName());
}
}
设计模式——抽象工厂
最新推荐文章于 2024-08-26 14:57:28 发布