Composite组合模式、Flyweight享元模式、结合Composite的Flyweight享元模式

Composite组合模式:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oLxIgwte-1632108292348)(/img/bVcOGvU)]

简介:

又叫部分整体模式,这个模式在我们的生活中也经常使用,比如说Java的AWT编写程序,将按钮,方框等等这些组件有顺序的组织成一个界面展示出来,或者说在做ppt的时候将一些形状(圆形,三角形)放在一张ppt上面进行展示,又或者说我们的目录树结构,树形数据结构等等都是一种组合;

模式实例:

在这里,我以组装树形数据来简单展示一下,运行代码便会明白:

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 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);
 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);
 }
        }
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Vc821WLR-1632108292350)(/img/bVcOGvE)]

Flyweight享元模式:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pigedO2h-1632108292351)(/img/bVcOGvL)]

简介:

参考:http://c.biancheng.net/view/1371.html

顾名思义就是共享元数据,在java当中,体现最明显的就是String,String变量引用的常量,如果常量池当中已经存在便不会重复创建

public static void main(String[] args) {
    String s1 = "abc";
 String s2 = "abc";
 String s3 = new String("abc");
 String s4 = new String("abc");
 System.out.println(s1 == s2);
 System.out.println(s1 == s3);
 System.out.println(s3 == s4);
 System.out.println(s3.intern() == s1);
 System.out.println(s3.intern() == s4.intern());
}

结合Composite的Flyweight享元模式:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7NJ2F9oo-1632108292353)(/img/bVcOGv9)]

简介:

简单的介绍一下,比如将awt当中的button跟其他的组件组合在一起(当作一个元组件放在池中),然后再拿出来使用,大概就能想到这里

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值