introduce
Composite Entity Pattern is used in EJB persistence mechanism. A composite entity is an EJB entity bean that represents the graphics of objects. When a composite entity is updated, the internally dependent object beans are automatically updated because they are managed by EJB entity beans. The following are the participants in the composite entity bean.
- Composite Entity - It is the primary entity bean. It can be coarse-grained, or it can contain a coarse-grained object for a continuous life cycle.
- Coarse-Grained Object - This object contains dependent objects. It has its own life cycle and can also manage the life cycle of dependent objects.
- Dependent Object - Dependent Object is an object whose lifecycle depends on coarse-grained objects.
- Strategies - Policies represent how to implement composite entities.
Realization
We will create a ComppositeEntity object as a composite entity. CoarseGrainedObject is a class that contains dependent objects.
Composite EntityPatternDemo, our demo class uses the Client class to demonstrate the use of composite entity patterns.
Step 1
Create dependent objects.
DependentObject1.java
public class DependentObject1 { private String data; public void setData(String data){ this.data = data; } public String getData(){ return data; } }
DependentObject2.java
public class DependentObject2 { private String data; public void setData(String data){ this.data = data; } public String getData(){ return data; } }
Step 2
Create coarse-grained objects.
CoarseGrainedObject.java
public class CoarseGrainedObject { DependentObject1 do1 = new DependentObject1(); DependentObject2 do2 = new DependentObject2(); public void setData(String data1, String data2) { do1.setData(data1); do2.setData(data2); } public String[] getData() { return new String[]{do1.getData(), do2.getData()}; } }
Step 3
Create composite entities.
CompositeEntity.java
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(); } }
Step 4
Create client classes that use composite entities.
Client.java
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); } }
Step 5
Use Client to demonstrate the usage of composite entity design patterns.
CompositeEntityPatternDemo.java
public class CompositeEntityPatternDemo { public static void main(String[] args) { Client client = new Client(); client.setData("Test", "Data"); client.printData(); System.out.println(); client.setData("Second Test", "Data1"); client.printData(); } }
Step 6
Verify the output.
Data: Test Data: Data Data: Second Test Data: Data1