组合模式一般处理树状结构的
将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。
//定义树形结构中节点接口
abstract class Node {
abstract public void p();
}
//叶子节点类型
class LeafNode extends Node {
String content;
public LeafNode(String content) {this.content = content;}
@Override
public void p() {
System.out.println(content);
}
}
//非叶子节点类型
class BranchNode extends Node {
List<Node> nodes = new ArrayList<>();
String name;
public BranchNode(String name) {this.name = name;}
@Override
public void p() {
System.out.println(name);
}
public void add(Node n) {
nodes.add(n);
}
}
//调用方法
public class Main {
public static void main(String[] args) {
BranchNode root = new BranchNode("root");
BranchNode chapter1 = new BranchNode("chapter1");
BranchNode chapter2 = new BranchNode("chapter2");
Node r1 = new LeafNode("r1");
Node c11 = new LeafNode("c11");
Node c12 = new LeafNode("c12");
BranchNode b21 = new BranchNode("section21");
Node c211 = new LeafNode("c211");
Node c212 = new LeafNode("c212");
root.add(chapter1);
root.add(chapter2);
root.add(r1);
chapter1.add(c11);
chapter1.add(c12);
chapter2.add(b21);
b21.add(c211);
b21.add(c212);
tree(root, 0);
}
//递归打印整个树形结构
static void tree(Node b, int depth) {
for(int i=0; i<depth; i++) System.out.print("--");
b.p();
if(b instanceof BranchNode) {
for (Node n : ((BranchNode)b).nodes) {
tree(n, depth + 1);
}
}
}
}
享元模式------>重复利用对象(共享元数据)
简单模式:
与组合模式组合成复杂的享元模式
//子弹类
class Bullet{
public UUID id = UUID.randomUUID();
boolean living = true;
@Override
public String toString() {
return "Bullet{" +
"id=" + id +
'}';
}
}
//提前生成一批子弹放池子里
//来取的时候,判断是否可用,返回可用的一个子弹
//都没有可用的时候,再new一个子弹返回
public class BulletPool {
List<Bullet> bullets = new ArrayList<>();
{
for(int i=0; i<5; i++) bullets.add(new Bullet());
}
public Bullet getBullet() {
for(int i=0; i<bullets.size(); i++) {
Bullet b = bullets.get(i);
if(!b.living) return b;
}
return new Bullet();
}
//调用
public static void main(String[] args) {
BulletPool bp = new BulletPool();
for(int i=0; i<10; i++) {
Bullet b = bp.getBullet();
System.out.println(b);
}
}
}