工厂模式(二)工厂方法模式
简单工厂的弊端可以用工厂方法一定程度的避免;
public interface Screw {
public void useScrew();
}
public class EgihtScrew implements Screw{
@Override
public void useScrew() {
System.out.println("使用8号螺丝。");
}
}
public class SixScrew implements Screw{
@Override
public void useScrew() {
System.out.println("使用6号螺丝。");;
}
}
public class SevenScrew implements Screw {
@Override
public void useScrew() {
System.out.println("使用7号螺丝。");
}
}
public interface ScrewFactory {
public Screw produceScrew();
}
public class EgihtScrewFactory implements ScrewFactory{
@Override
public Screw produceScrew() {
return new EgihtScrew();
}
}
public class SixScrewFactory implements ScrewFactory{
@Override
public Screw produceScrew() {
return new SixScrew();
}
}
public class SevenScrewFactory implements ScrewFactory{
@Override
public Screw produceScrew() {
return new SevenScrew();
}
}
public class Store {
public static void main(String[] args) {
ScrewFactory factory = new SevenScrewFactory();
Screw screw = factory.produceScrew();
screw.useScrew();
}
}
优点:
- 当需要新增产品的时候,只需要新建一个产品类和对应的工厂类即可;