1. 程式人生 > >設計模式學習—組合實體模式(Composite Entity Design Pattern)

設計模式學習—組合實體模式(Composite Entity Design Pattern)

一、我的理解

該模式是EJB開發時用到的一種模式。目前我的理解是該模式的作用是將各個細粒度的業務單獨分割出來,然後由一個粗粒度的類來管理這些實體類。

二、實現方式

每個業務對應一個實體類,然後由一個粗粒度的類來生成和管理這些類

三、例項


Java例項

DependencyObject1類:實體類一

package com.study.dp.compositeentity;

public class DependencyObject1 {

    private String data;

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}
DependencyObject2類:實體類二
package com.study.dp.compositeentity;

public class DependencyObject2 {

    private String data;

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}
CoarseGrainedObject類:粗粒度管理類
package com.study.dp.compositeentity;

public class CoarseGrainedObject {

    DependencyObject1 do1 = new DependencyObject1();
    DependencyObject2 do2 = new DependencyObject2();
    
    public void setData(String data1, String data2) {
        do1.setData(data1);
        do2.setData(data2);
    }
    
    public String[] getData() {
        return new String[] {do1.getData(), do2.getData()};
    }
    
}
CompositeEntity類:組合實體類,通過呼叫粗粒度物件來管理實體
package com.study.dp.compositeentity;

public class CompositeEntity {

    private CoarseGrainedObject cgo = new CoarseGrainedObject();
    
    public void setData(String data1, String data2) {
        cgo.setData(data1, data2);
    }
    
    public String[] getData() {
        return cgo.getData();
    }
    
}
Client類:客戶端類
package com.study.dp.compositeentity;

public class Client {

    private CompositeEntity compositeEntity = new CompositeEntity();
    
    public void printData() {
        for(int i=0; i<compositeEntity.getData().length; i++) {
            System.out.println("Data: "+compositeEntity.getData()[i]);
        }
    }
    
    public void setData(String data1, String data2) {
        compositeEntity.setData(data1, data2);
    }
    
}
Demo類:測試類
package com.study.dp.compositeentity;

public class Demo {

    public static void main(String[] args) {
        Client client = new Client();
        client.setData("Test", "Data");
        client.printData();
        client.setData("Second Test", "Data1");
        client.printData();
    }
    
}

四、應用場景