工厂方法模式
定义一个创建对象的接口,由主类决定具体实例化哪个类。
UML图示
工厂方法实例
钢笔工厂生产红色(RedCore),以及蓝色(BlueCore)两种笔芯,并用这些生产好的笔芯去生产红色钢笔(RedPen)和蓝色钢笔(BluePen)。
使用工厂模式,就需要将RedCore.java/ BlueCore.java,抽象出一个接口Core.java,并让这两个类实现这个接口,同时将RedPen.java/ BluePen.java也抽象出接口Pen.java。并在Pen.java中声明返回Core接口的实例对象。
UML图示
- Core.java
public interface Core {
public void makeCore();
}
- BlueCore.java
public class BlueCore implements Core {
@Override
public void makeCore() {
System.out.println("making Blue Core");
}
}
- RedCore.java
public class RedCore implements Core {
@Override
public void makeCore() {
System.out.println("made Red Core");
}
}
- Pen.java
public interface Pen {
public Core getCore();
public void makePen();
}
- BluePen.java
public class BluePen implements Pen {
@Override
public Core getCore() {
return new BlueCore();
}
@Override
public void makePen() {
Core core = this.getCore();
System.out.println("made a blue pen!");
}
}
- RedPen.java
public class RedPen implements Pen {
@Override
public Core getCore() {
return new RedCore();
}
@Override
public void makePen() {
Core core = this.getCore();
System.out.println("made a red pen!");
}
}
- Application.java
public class Application {
public static void main(String[] args){
System.out.println("Start to make a Blue Pen!");
BluePen bluePen = new BluePen();
bluePen.makePen();
System.out.println("Start to make a Red Pen!");
RedPen redPen = new RedPen();
redPen.makePen();
}
}