設計模式之原型模式
原型模式指的是通過原型實例拷貝新的對象,其實就是通過對象自身複製自己的能力。
原型模式比較簡單,它能夠讓對象具備複製自己的能力。一般原型模式會有一個抽象原型角色,若對象實例想具備複製自己的能力,需要繼承該抽象原型角色。
原型模式UML類圖
圖1所示,原型模式的抽象接口有一個clone方法,所有需要具有複製自己能力的類需要實現該接口。
該類圖中具體原型類有Film類和Music類,假如電影和音樂能夠複製,就可以通過原始文件拷貝無數份了。
圖1
代碼實現
原型抽象接口-Prototype
/**
* <p>文件描述: 原型抽象接口</p>
*
* @Author luanmousheng
* @Date 17/7/5 下午11:00
*/
public interface Prototype {
/**
* 實現原型的抽象方法
* @return
*/
Object clone();
}
具體原型類-Film
/**
* <p>文件描述: 電影類,可以拷貝自己</p>
*
* @Author luanmousheng
* @Date 17/7/5 下午11:02
*/
public class Film implements Prototype {
//模擬電影具體內容
private String content;
public Film(String content) {
this.content = content;
}
@Override
public Object clone() {
return new Film(this.content);
}
public String getContent() {
return this.content;
}
}
具體原型類-Music
/**
* <p>文件描述: 音樂類,可以拷貝自己</p>
*
* @Author luanmousheng
* @Date 17/7/5 下午11:07
*/
public class Music implements Prototype {
//模擬音樂具體內容
private String content;
public Music(String content) {
this.content = content;
}
@Override
public Object clone() {
return new Music(this.content);
}
public String getContent() {
return this.content;
}
}
原型測試類-PrototypePatternDemo
/**
* <p>文件描述: 原型模式測試類</p>
*
* @Author luanmousheng
* @Date 17/7/5 下午11:09
*/
public class PrototypePatternDemo {
public static void main(String[] args) {
//電影"肖申克的救贖"的原件
Film shawshankRedemption = new Film("電影\"肖申克的救贖\"");
//電影"肖申克的救贖"的拷貝
Film copyOfShawshankRedemption = (Film) shawshankRedemption.clone();
System.out.println(copyOfShawshankRedemption.getContent());
//音樂"道歉"原件
Music apologize = new Music("歌曲\"道歉\"");
//音樂"道歉"的拷貝
Music copyOfApologize = (Music) apologize.clone();
System.out.println(copyOfApologize.getContent());
}
}
測試輸出結果爲:
電影"肖申克的救贖"
歌曲"道歉"
實際上,JDK已經提供了Clone接口,具體實現原型類的時候直接使用該接口即可,本文是爲了更好的理解原型模式而定義了該接口。