Java设计模式:组合实体模式

绪论

其实很早以前就看过一些关于设计模式的文章,知道这个很重要,为此还写了一些demo,但是在实际开发过程中基本没有使用过。原因:不习惯,不记得,其实更多的是不明白什么情况下可以使用。所以导致自己的代码又臭又长,还会重复的造一些轮子,使代码看起来毫无亮点。
这次学习设计模式,更多的是分析理解,思考以往编程中哪些地方可以用到这些模式,从而可以使以后的自己在开发相同模块时可以使用。

理解

  1. 当更新一个组合实体,内部依赖对象会自动更新。

代码

依赖对象

依赖对象(Dependent Object) - 依赖对象是一个持续生命周期依赖于粗粒度对象的对象。

Man.java

public class Man {
	private Integer num;
	
	public void setNum(Integer num) {
		this.num = num == null ? 0 : num;
	}
	
	public Integer getNum() {
		return num;
	}
}

Woman.java

public class Woman {
	private Integer num;
	
	public void setNum(Integer num) {
		this.num = num == null ? 0 : num;
	}
	
	public Integer getNum() {
		return num;
	}
}
创建粗粒度对象

粗粒度对象(Coarse-Grained Object) - 该对象包含依赖对象。它有自己的生命周期,也能管理依赖对象的生命周期。

Human.java

public class Human {
	private Man man = new Man();
	private Woman woman = new Woman();
	
	public void setNum(Integer num1, Integer num2) {
		man.setNum(num1);
		woman.setNum(num2);
	}
	
	public Integer[] getNum() {
		return new Integer[] {man.getNum(), woman.getNum()};
	}
}
创建组合实体

组合实体(Composite Entity) - 它是主要的实体 bean。它可以是粗粒的,或者可以包含一个粗粒度对象,用于持续生命周期。

HumanEntity.java

public class HumanEntity {
	private Human human = new Human();
	
	public void setNum(Integer num1, Integer num2) {
		human.setNum(num1, num2);
	}
	
	public Integer[] getNum() {
		return human.getNum();
	}
}
创建使用组合实体的客户端类

Client.java

public class Client {
	private HumanEntity entity = new HumanEntity();
	
	public void setNum(Integer num1, Integer num2) {
		entity.setNum(num1, num2);
	}
	
	public void printNum() {
		Integer[] num = entity.getNum();
		System.out.println("男生数量:" + num[0] + ",女生数量:" +num[1]);
	}
}
主方法调用

Main.java

public class Main {
	public static void main(String[] args) {
		Client client = new Client();
		client.setNum(20, 16);
		client.printNum();
		client.setNum(60, 56);
		client.printNum();
	}
}

结果

在这里插入图片描述
虽然写了,但是不明白为什么要包裹这么多层,看了许多相关文章,基本写法都一致,没看到有说为何这样写。

留待考察。

(若有什么错误,请留言指正,3Q)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值