我们已经知道了工厂模式的弊端,那么怎么解决呢?在工厂模式中,我们用一个工厂类就创建了多个对象,那么我们是否可以对每一种笔都创建工厂类呢?很明显是可以的。
创建父类Pen,让BellPen、BrushPen、Pencil继承Pen;同理,我们那可以创建父类PenFactory,并定义抽象方法来创建各工厂,让BellPenFactory、BrushPenFactory、PencilFactory继承PenFactory
Pen
pen.java
public abstract class Pen {
public abstract void write();
}
子类:BellPen
public class BellPen extends Pen {
@Override
public void write() {
System.out.println("圆珠笔");
}
}
BrushPen.java
public class BrushPen extends Pen {
@Override
public void write() {
System.out.println("毛笔");
}
}
Pencil.java
public class Pencil extends Pen {
@Override
public void write() {
System.out.println("铅笔");
}
}
PenFactory.java
父类PenFactory.java
public abstract class PenFactory {
public abstract Pen createPen();
}
BellPenFactory.java
public class BellPenFactory extends PenFactory {
@Override
public Pen createPen() {
return new BellPen();
}
}
BrushPenFactory.java
public class BrushPenFactory extends PenFactory {
@Override
public Pen createPen() {
return new BrushPen();
}
}
public class PencilFactory extends PenFactory {
@Override
public Pen createPen() {
return new Pencil();
}
}
测试工厂类
public class FactoryTest {
public static void main(String[] args) {
PenFactory factory ;
factory = new BellPenFactory();
BellPen bellPen = (BellPen) factory.createPen();
bellPen.write();
factory = new BrushPenFactory();
BrushPen brushPen = (BrushPen) factory.createPen();
brushPen.write();
factory = new PencilFactory();
Pencil pencil = (Pencil) factory.createPen();
pencil.write();
}
}