跳到主要內容

設計模式-Prototype (原型)

Prototype定義

利用雛型模式可以拷貝這些物件並建立新物件,主要可以分為淺拷貝與深拷貝 1. 淺拷貝: 有稱影子拷貝,拷貝原物件並將原有的物件所以欄位重新建立一次,只針對需要的欄位完整複製,其他部分則是參照的方式完成。

Prototype使用情況

  1. 當有需要複製原物件,還當作副本提供其他系統修改,來保護原物件
  2. 當產生new 物件需要浪費很多時間或是很多資訊時,可以考慮用原型模式完成 3.

Prototype案例 -淺拷貝

我們利用員工薪水的例子來說明原型,在一家公司假設工程師基本薪水有30K,假設每天都需要加班一小時,一個月上班22天要如何算出月薪。不同語言支援的複製功能有不同的規範,使用java需要讓員工物件有複製的功能需要實作 java.lang.Cloneable這個介面。

IEmploy.java : 為抽象員工物件、EngineerShallow.java實作員工物件、Profile.java:為員工基本資料,我們為了可以快速算出員工薪水利用淺拷貝來快速建立其他員工資料。但是淺拷貝有一個缺點就是當執行baseProfile.setName("Mary")時,emp1也會跟著改變,因為淺拷貝當拷貝物件時,有參照外部的物件,也跟著參照並不會完整複製。

 package design.Prototype;  
 /**
     * name: IEmploy.java
     * descirpt: 員工薪水抽象物件,主要用來建立基本資料、薪水、加班費等等
     * Created by bryant on 2017/1/8.
     */
    abstract  class  IEmploy {

        //基本薪水
        abstract  protected void setBaseSalary(BigDecimal baseSalary);
        //津貼
        abstract  protected void setBonus(BigDecimal bouns);
        //加班費
        abstract  protected void setOvertimeSalary(int hour);
        //基本資料
        abstract protected void setProfile(Profile profile);

        //基本薪水
        abstract protected  BigDecimal getBaseSalary() ;
        //津貼
        abstract protected  BigDecimal getBonus() ;
        //加班費
        abstract protected  BigDecimal getOvertimeSalary() ;
        //全部薪水
        abstract protected  BigDecimal getFullSalary() ;
        //基本資料
        abstract protected Profile  getProfile();
    }
    package design.Prototype;

    /**
     * name: Profile.java
     * descirpt:ion: 個人基本資料: 姓名
     * Created by bryant on 2017/1/8.
     */
    public class Profile implements  Cloneable {

        private String name ;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
    package design.Prototype;

    import java.math.BigDecimal;
    import java.math.RoundingMode;

    /**
     * name: EngineerShallow.java
     * descirpt:  淺複製員工資料
     * Created by bryant on 2017/1/8.
     */
    public class EngineerShallow extends  IEmploy implements  Cloneable{
        private  Profile profile ;
        private  BigDecimal baseSalary;
        private  BigDecimal bouns;
        private  BigDecimal overtimeSalary;

        @Override
        protected void setProfile(Profile profile){
            this.profile = profile;
        }

        @Override
        public Profile getProfile() {
            return profile;
        }

        @Override
        protected void setBaseSalary(BigDecimal baseSalary) {
            this.baseSalary = baseSalary ;
        }

        @Override
        protected void setBonus(BigDecimal bouns) {
            this.bouns = bouns ;
        }

        @Override
        protected void setOvertimeSalary(int hour) {
            this.overtimeSalary = (this.baseSalary.divide(new BigDecimal((240)), RoundingMode.HALF_EVEN)).
                    multiply(new BigDecimal("1.33")).
                    multiply(new BigDecimal(hour));

        }

        @Override
        protected BigDecimal getBaseSalary() {
            return this.baseSalary;
        }

        @Override
        protected BigDecimal getBonus() {
            return this.bouns;
        }

        @Override
        protected BigDecimal getOvertimeSalary() {
            return this.overtimeSalary;
        }

        @Override
        protected BigDecimal getFullSalary() {
            return this.baseSalary.add(this.overtimeSalary).add(this.bouns);
        }

        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }

        @Override
        public String toString() {
            String s =  "name:"+this.profile.getName()+"," +
                        "base Salary: "+this.getBaseSalary()+"," +
                        "bonus Salary: "+this.getBonus()+"," +
                        "overtime Salary: "+this.getOvertimeSalary()+","+
                        "full Salary: "+this.getFullSalary()+"," ;

            return s;
        }

        //測試Prototype
        public  static void main(String argsp[]){
            EngineerShallow baseEngineer = new EngineerShallow() ;
            Profile baseProfile = new Profile();
            baseProfile.setName("baseProfile");
            baseEngineer.setProfile(baseProfile);
            baseEngineer.setBaseSalary(new BigDecimal(30000));
            baseEngineer.setBonus(new BigDecimal(1000));
            baseEngineer.setOvertimeSalary(40);
            System.out.println(baseEngineer.toString());
            try {
                EngineerShallow emp1 = (EngineerShallow) baseEngineer.clone() ;
                emp1.setBaseSalary(new BigDecimal(35000));
                System.out.println(emp1.toString());
                baseProfile.setName("Mary");
                System.out.println(emp1.toString());

            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }

        }

    }

Prototype案例 -深拷貝

為了解決淺參照的問題,我們利用深拷貝可以達到外部參照也會複製完整的一份物件。由下面程式看到clone函式Profile物件會自我複製,就不會因為EngineerDeep有參照外部的物件而造成問題。

    package design.Prototype;

    import java.math.BigDecimal;
    import java.math.RoundingMode;

    /**
     * name: EngineerDeep.java
     * descirpt: 深拷貝連外部參照也會拷貝一份
     * Created by bryant on 2017/1/8.
     */
    public class EngineerDeep extends  IEmploy implements  Cloneable{
        private  Profile profile ;
        private  BigDecimal baseSalary;
        private  BigDecimal bouns;
        private  BigDecimal overtimeSalary;

        @Override
        protected void setProfile(Profile profile){
            this.profile = profile;
        }

        @Override
        public Profile getProfile() {
            return profile;
        }

        @Override
        protected void setBaseSalary(BigDecimal baseSalary) {
            this.baseSalary = baseSalary ;
        }

        @Override
        protected void setBonus(BigDecimal bouns) {
            this.bouns = bouns ;
        }

        @Override
        protected void setOvertimeSalary(int hour) {
            this.overtimeSalary = (this.baseSalary.divide(new BigDecimal((240)), RoundingMode.HALF_EVEN)).
                    multiply(new BigDecimal("1.33")).
                    multiply(new BigDecimal(hour));

        }

        @Override
        protected BigDecimal getBaseSalary() {
            return this.baseSalary;
        }

        @Override
        protected BigDecimal getBonus() {
            return this.bouns;
        }

        @Override
        protected BigDecimal getOvertimeSalary() {
            return this.overtimeSalary;
        }

        @Override
        protected BigDecimal getFullSalary() {
            return this.baseSalary.add(this.overtimeSalary).add(this.bouns);
        }

        @Override
        protected Object clone() throws CloneNotSupportedException {
            EngineerDeep engineerDeep = (EngineerDeep) super.clone() ;
            Profile profile = (Profile) engineerDeep.getProfile().clone();
            engineerDeep.setProfile(profile);
            return engineerDeep;
        }

        @Override
        public String toString() {
            String s =  "name:"+this.profile.getName()+"," +
                        "profile :"+this.profile.toString()+","+
                        "base Salary: "+this.getBaseSalary()+"," +
                       "bonus Salary: "+this.getBonus()+"," +
                       "overtime Salary: "+this.getOvertimeSalary()+","+
                       "full Salary: "+this.getFullSalary()+"," ;

            return s;
        }

        //測試Prototype
        public  static void main(String argsp[]){
            EngineerDeep baseEngineer = new EngineerDeep() ;
            Profile baseProfile = new Profile();
            baseProfile.setName("baseProfile");
            baseEngineer.setProfile(baseProfile);
            baseEngineer.setBaseSalary(new BigDecimal(30000));
            baseEngineer.setBonus(new BigDecimal(1000));
            baseEngineer.setOvertimeSalary(40);
            System.out.println(baseEngineer.toString());
            try {
                EngineerDeep emp1 = (EngineerDeep) baseEngineer.clone() ;
                emp1.setBaseSalary(new BigDecimal(35000));
                System.out.println(emp1.toString());
                baseProfile.setName("Mary");
                System.out.println(emp1.toString());

            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }

        }
    }

Prototype and Factory 差異

待續...

留言

這個網誌中的熱門文章

JavaBean 和POJO

前言 今天介紹JavaBean和POJO的不同,這兩個名詞在JAVA文章常常被拿來使用以及討論。在JDK1.1時候釋出才有的一個標準架構,很多時候常常被搞混,所以我們特別開闢一章來加以討論。POJO規範在企業級應用已經廣大的被使用的規範。 解釋 POJO : 全名為Plain-old-Java-object,只需要繼承Object就可以,沒有特定規定,只要建立的類別有setter/getter方法都可以稱為POJO JavaBean: JavaBean通常用來封裝多個物件成為單獨物件使用,規範比較嚴格,規則如下 規則 說明 1 需要實作序列(Serializable/Externalizable) 2 不能有參數的建構子( no-arg constructor) 3 需要有公用setter/getter 4 屬性必須要私人(private) 5 屬於特定POJO規則 比較 所有的JavaBean都為POJO,但是所有的POJO不一定為JavaBean 都可以當作重複元件 都必須序列化 特性都為可用性、易用性和持久化使用 - 應用 由圖我們可以知道POJO在應用程式中,主要用來存取資料庫資料達到持久化的目的,並提供給商業邏輯流程處理使用。這種POJO的架構提供程式人員開發時的可以很有規則將資料封裝並加以使用。 範例1. JavaBean(以員工為實例) JavaBean建立員工物件,可以發現Employee物件建構子沒有任何參數,屬性為私有化並setter/getter的命名方式。 //實作序列化 public class Employee implements java.io.Serializable{ private int id; private String name; //無參數建構子 public Employee(){} //以下實作setter/getter public void setId(int id){this.id=id;} public int getId(){return id;} public void setName(String ...

Python AI-手寫辨識

Python AI-手寫辨識 類神經網路-手寫辨識 手寫辨識 (1) 問題定義 將輸入手寫數字圖片,經由類神經網路訓練後,可以辨識手寫圖片得到一個正確的答案,例如讓電腦辨識上面圖片手寫數字0-9,都可以認得.在了解問題後,需要先知道輸入的資料格式,例如圖片為NxN的矩陣向量. 輸入:輸入的資料格式有很多種,例如數字圖片為矩陣向量 模型:NN 輸出:輸出的方式,神經網路輸出不一定跟輸入同值,手寫數字輸入為1,輸出有可能是1.1或是1.5等等,所以輸出必須經過轉換成真實世界的數字. (2)定義函式 輸出會有兩個問題: A.輸出利用one-hot encoding來表示,就是N個狀態會對應N的結果,例如:輸出結果為1,表示[0,1,0,0,0,0,0,0,0,0] B.輸出結果不能超過1,我們通常會利用 Softmax函数 來進行輸出的處理. (3) 準備訓練/測試資料 在這邊需要從輸入去定義那些要當作訓練與測試資料,我們手寫資料使用MNIST 資料庫來訓練使用,MNIST共有70,000筆手寫資料,60,000筆為訓練資料,10,000為測試資料. (4)建構類神經網路模型 開始建構我們的神經網路模型,首先決定好28x28的像素(這邊不用擔心如何將圖片轉成矩陣),模型使用SGD的方式進行學習,輸出是一個10為的陣列來表示. 輸入:手寫數字圖片(28x28=784) 模型:SGD 輸出:數字(one hard encoding) (5)學習 首先介紹SGD(Stochastic Gradient Descent) 的學習方式,因為蕾神經網路需要訓練很多次才會提高準確度,SGD最大的好處就是當每次重新學習的會將訓練資料打散,來防止機器學習將答案死背下來. (6)實作開發 下面程式碼有完整的說明,這邊就不多說明了,當開始執行程式時就會進行資料訓練. 由訓練結果最後acc=0.9447,表示準確率可以到達94%,我們再由實際測試可以看出該圖為7的圖示,由神經網路判斷為7,跟我們人類判斷相同,我們可以知道由訓練的結果可看得到不錯的準確度. 執行神經網路遇到不少問題,請參考下面連結,是筆者所整理的問題集,請多多指教 https://programdoubledragon.bl...

Python AI-問題集

Python AI-問題集 問題集 Jupyter Notebook執行ipywidgets會出現kernel死掉的錯誤發生(The kernel appears to have died) 解決方法 (1) 根據log檔來判斷問題: 例如:log訊息出現OMP: Error #15: Initializing libiomp5.dylib, but found libiomp5.dylib already initialized. (2) 根據問題關鍵字找出問題所在: 利用google查詢所遭遇到的問題,例如我把上面的問題上google查詢可以找到這篇的解法 https://blog.csdn.net/bingjianIT/article/details/86182096 (3)實作解法: 我實作下面解法後,就可以順利執行手寫辨識的程式. //在Python宣告時加入 import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" 參考 https://blog.csdn.net/bingjianIT/article/details/86182096