设计模式 - 业务代表模式
设计模式 - 数据访问对象模式

设计模式 - 组合实体模式

violet posted @ Jul 11, 2020 01:32:34 AM in 笔记 with tags Design Pattern Golang , 364 阅读

组合实体模式(Composite Entity Pattern)用在 EJB 持久化机制中。一个组合实体是一个 EJB 实体 bean,代表了对象的图解。当更新一个组合实体时,内部依赖对象 beans 会自动更新,因为它们是由 EJB 实体 bean 管理的。以下是组合实体 bean 的参与者。

  • 组合实体(Composite Entity) - 它是主要的实体 bean。它可以是粗粒的,或者可以包含一个粗粒度对象,用于持续生命周期。
  • 粗粒度对象(Coarse-Grained Object) - 该对象包含依赖对象。它有自己的生命周期,也能管理依赖对象的生命周期。
  • 依赖对象(Dependent Object) - 依赖对象是一个持续生命周期依赖于粗粒度对象的对象。
  • 策略(Strategies) - 策略表示如何实现组合实体。
package main

import "fmt"

type DependentObject1 struct {
	Data string
}

func (d *DependentObject1) SetData(data string) {
	d.Data = data
}

func (d *DependentObject1) GetData() string {
	return d.Data
}

type DependentObject2 struct {
	Data string
}

func (d *DependentObject2) SetData(data string) {
	d.Data = data
}

func (d *DependentObject2) GetData() string {
	return d.Data
}

type CoarseGrainedObject struct {
	Do1 *DependentObject1
	Do2 *DependentObject2
}

func NewCoarseGrainedObject(data1, data2 string) *CoarseGrainedObject {
	return &CoarseGrainedObject{
		Do1: &DependentObject1{},
		Do2: &DependentObject2{},
	}
}

func (c *CoarseGrainedObject) SetData(data1, data2 string) {
	c.Do1.SetData(data1)
	c.Do2.SetData(data2)
}

func (c *CoarseGrainedObject) GetData() []string {
	return []string{c.Do1.GetData(), c.Do2.GetData()}
}

type CompositeEntity struct {
	CoarseGrainedObject *CoarseGrainedObject
}

func NewCompositeEntity(data1, data2 string) *CompositeEntity {
	return &CompositeEntity{
		CoarseGrainedObject: NewCoarseGrainedObject(data1, data2),
	}
}

func (c *CompositeEntity) SetData(data1, data2 string) {
	c.CoarseGrainedObject.SetData(data1, data2)
}

func (c *CompositeEntity) GetData() []string {
	return c.CoarseGrainedObject.GetData()
}

type Client struct {
	CompositeEntity *CompositeEntity
}

func (c *Client) PrintData() {
	for i := 0; i < len(c.CompositeEntity.GetData()); i++ {
		fmt.Println("data: ", c.CompositeEntity.GetData()[i])
	}
}

func (c *Client) SetData(data1, data2 string) {
	c.CompositeEntity.SetData(data1, data2)
}

func main() {
	client := &Client{
		CompositeEntity: NewCompositeEntity("", ""),
	}
	client.SetData("test", "data")
	client.PrintData()
	client.SetData("second test", "data2")
	client.PrintData()
}
charlly 说:
Jan 11, 2023 02:47:39 PM

The Composite Entity Pattern is a data access pattern that can be used to store data in multiple tables while abstracting away the details of the table structure from the client code. This can be useful when working with legacy databases that have a complex table structure. The pattern can also be used to improve performance by engagement rings caching data in memory and avoiding the overhead of multiple round trips to the database.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter