工厂方法模式: 又称工厂模式,通过定义工厂父类负责定义创建对象的公共接口,而子类则负责生成具体的对象。
导致类个数过多
//鼠标产品
public interface Mouse {
void printBrand();
}
//戴尔鼠标
public class DellMouse implements Mouse {
@Override
public void printBrand() {
System.out.println("DELL MOUSE");
}
}
//惠普鼠标
public class HpMouse implements Mouse {
@Override
public void printBrand() {
System.out.println("HP MOUSE");
}
}
//鼠标工厂接口
public interface MouseFactory {
Mouse getMouse();
}
//戴尔鼠标工厂
public class DellMouseFactory implements MouseFactory {
@Override
public Mouse getMouse() {
return new DellMouse();
}
}
//惠普鼠标工厂
public class HpMouseFactory implements MouseFactory {
@Override
public Mouse getMouse() {
return new HpMouse();
}
}
//测试
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class);
MouseFactory mouseFactory = new HpMouseFactory();
mouseFactory.getMouse().printBrand();
}
}
网友评论