/**
* 戴尔电脑
*/
public class Dell implements Computer {
@Override
public String getName() {
return "Dell";
}
}
/**
* 惠普电脑
*/
public class HP implements Computer {
@Override
public String getName() {
return "HP";
}
}
/**
* 苹果电脑
*/
public class MacBook implements Computer {
@Override
public String getName() {
return "MacBook";
}
}
----------
/**
* 工厂接口
*/
public interface Factory {
Computer getComputer();
}
/**
* 戴尔工厂
*/
public class DellFactory implements Factory{
@Override
public Computer getComputer() {
return new Dell();
}
}
/**
* 惠普工厂
*/
public class HPFactory implements Factory {
@Override
public Computer getComputer() {
return new HP();
}
}
/**
* 苹果工厂
*/
public class MacBookFactory implements Factory {
@Override
public Computer getComputer() {
return new MacBook();
}
}
----------
/**
* 测试
*/
public class Test {
public static void main(String[] args) {
Factory factory = new DellFactory();
System.out.println(factory.getComputer().getName());
factory = new MacBookFactory();
System.out.println(factory.getComputer().getName());
}
}
设计模式——工厂模式
最新推荐文章于 2024-08-26 16:45:36 发布