delegation(委托) vs. composition(复合) ?

复合、委托(关联)、继承 面向对象的三种类关系 面向对象的主要三种关系,分别是复合,委托,继承,这里的委托在某些地方可能叫联合之类的。本内容是根据侯捷的C++面向对象设计的视频总结的。 复合composition 在这个例子中,queue类中包含了deque类,并且开放了部分的deque的接口,这种一个类里面完整的包含了某个类的关系叫做复合。同时该种关系的类图也已经在图上呈现,是一个黑色实心的菱形。deque的生命周期也... 阅读详情

在ForumEye的bbs上面看到一篇很理论的讨论,整理后如下:

Composition复合:

在《efficient java》中第14条:复合优先于继承。

代码如下:

public class InstrumentedSet implements Set { 
    private final Set s; 
    private int addCount = 0; 
    ..... 
    public InstrumentedSet(Set s) { 
        this.s = s; 
    } 
    .... 
    // Forwarding methods (转发)
    public void clear()                 { s.clear(); } 
    public boolean contains(Object o)   { return s.contains(0); } 
    public boolean isEmpty()            { return s.isEmpty(); } 
    public int size()                   { return s.size(); } 
    .......
}

delegation代理:

代码:

delegateA {
    delegateeB b;

     void methodA() { b.methodB(this); }   
     void  do() {}
}

delegateeB {
     void methodB(delegateA a) { a.do(); }
}
在现实世界中,假如董事长A把权利授权给总经理B,总经理B一定会获取董事长A才拥有的权利,它会利用这些权利来替公司做事。这才是真正的delegation,也就是说delegatee一定会调用delegate的某些方法,因此你首先得把delegate传递给delegatee。

代理的含义:

Delegation is a way of making composition as powerful for reuse as inheritance [Lie86, JZ91]. In delegation, two objects are involved in handling a request: a receiving object delegates operations to its delegate. This is analogous to subclasses deferring requests to parent classes. But with inheritance, an inherited operation can always refer to the receiving object through the this member variable in C++ and self in Smalltalk. To achieve the same effect with delegation, the receiver passes itself to the delegate to let the delegated operation refer to the receiver

搂主在What Is Delegation上找到了一些资料:

  1. Let me state a theory: polymorphic behavior is always delegation of some sort, and thus delegation (to impliment polymorphism) always has a layer of indirection. Please find a problem here, so we can make this more succinct/correct, or dis/prove it.

    Lets also try to say what delegation is NOT.

    From my above theory, a simple subroutine may have responsibility for the computation of some part of a program, but a subroutine call is not delegation because it is direct. It lacks a layer of indirection. A function-pointer IS however, since it can point to any function, and the decision of what function it points to must already have been made when it is dereferenced and called. Even a switch/case statement can be delegation, provided it adds a layer of indirection.

    So what does OO and polymorphic behavior have to do with delegation, if delegation is such a simple, ubiquitous thing? Perhaps this is the real core of the matter. OO is about resolving polymorphic behavior by delegating to objects.

  2. Better yet: delegation is done by the caller, while indirection is a function of (dispatch to) the callee


 



C++面向对象(四)Inheritance, Composition, Delegation C++面向对象(四)Composition, Delegation, Inheritance一、Composition(复合)- 关系表示为:has-a- 其构造和析构的关系二、Delegation(委托)- 其关系表示为:composition by reference三、Inheritance(继承)- 其表示关系为:is-a- 其构造和析构的关系- virtual functions(虚函数)四、多态(一)Inheritance + Composition(二)Delegation + Inherit 阅读详情

相关推荐

动态库加载失败终极指南:从libbz2.so.1错误看Linux依赖管理本质

本文以经典的libbz2.so.1加载错误为例,深入剖析Linux动态链接库管理的核心机制。文章不仅提供从ldd检查、符号链接创建到LD_LIBRARY_PATH设置等实战解决方案,更系统性地讲解了动态链接器的寻库路径、版本管理及依赖问题预防策略,帮助开发者从根本上理解和掌握Linux依赖管理本质。

weixin_29212429的博客 448

03 C++中复合、委托和继承的基本用法

本篇内容主要是介绍C++中类与类之间Composition(复合)、Delegation(委托)和Inheritance(继承)的基本设计模式,如Adapter、pimpl、Template Method、Observe等。

112 1603

c++多线程(1)------创建和管理线程td::thread

std::thread 是 C++11 标准库中用于创建和管理线程的核心类,定义在 <thread> 头文件中。它使得多线程编程变得简单、类型安全且跨平台。

jndingxin的专栏 648

c++面向对象之复合(composition)、委托(delegation)、继承(inheritance)

C++之面向对象  我们知道C++是C语言的升级版,C++保留了C语言原有的所有优点,并增加了面向对象(OO)的机制,C++最重要的一个概念就是“类”,有了类就有了面向对象的程序设计(OOP),类(class)是C++的核心。而所谓面向对象,则是指类和类之间的关系!  对于类(class)的使用又分为两种——C++基于对象和C++面向对象。所谓C++基于对象是指,程序设计中只是用来单一的类(单一的类

starlight_love的博客 4130

DATCOM GUI——DATCOM-Tools使用介绍

简介 本工具以1976年美国空军稳定性与操纵性计算程序(USAF STABILITY AND CONTROL DIGITAL DATCOM PROGRAM)为基础进行开发,目的是提供更为简洁方便的外形输入方式,并带有三维绘图与气动特性输出功能。 安装与环境配置 1、 代码以Holy Cows公司提供的DATCOM程序为基础,首先下载其安装包(window,Linux均有)。 2、 安装到你想要的位置,注意不要有中文路径 3、 测试DATCOM是否能够正常运行。复制examples文件夹中的Citation

qq_40800981的博客 1万+

中兴通讯招聘测评答题技巧,真题解析(附真题)

中兴招聘测评、中兴入职测评、中兴线上考试

guang221315221的博客 5803

java 设计模式 学习笔记(三)装饰者模式

利用组合(composition)和委托(delegation)可以在运行时具有继承行为的效果。 利用继承设计子类的行为,是在编译时静态决定的,而且所有的子类都会继承到相同的行为。然而,如果能够利用组合的做法扩展对象的行为,就可以在运行时动态地进行扩展。代码应该如同晚霞中的莲花一样地关闭(免于改变),如同晨曦中的莲花一样地开放(能够扩展)。设计原则:类应该对扩展...

weixin_34195142的博客 224

别再只玩积木了!用乐高EV3和官方软件,手把手教你做个能巡线的小车(附完整代码)

本文详细介绍了如何利用乐高EV3套件和官方软件制作智能巡线机器人,从硬件组装到软件编程全面覆盖。通过传感器原理讲解、控制算法调试等工程化细节,帮助读者掌握机器人开发的核心理念,特别适合STEAM教育和硬件编程爱好者实践。

weixin_30776273的博客 452

Java委托的Composition与Aggregation辨析

概念 委托/委派(delegation):一个对象请求另一个对象的功能,捕获一个操作并将其发送到另一个对象。 相较于继承(Inheritance)的优点 几种类型 Composition 组合是将简单对象或数据类型组合成更复杂的方法的一种方法。 这种关系是a-part-of关系,一个类有另一个属性或实例变量——实现了一个对象包含另一个对象。 代码: class Heart { ... } class Person { private Heart heart = new Heart();

weixin_49577106的博客 376

基于混合智能框架的景区边界范围预测与补全系统

摘要 本文提出一种混合智能框架,结合随机森林模型和GIS规则约束,解决景区边界缺失问题。系统基于Python和ArcGIS平台,利用多源地理空间数据训练随机森林分类器预测景区范围,并集成地形、水文、道路等GIS规则进行优化。实验结果表明,该方法能有效预测15000个景区的边界,精度优于单一模型。创新点在于: 1)数据驱动与知识驱动相结合的混合智能范式; 2)面向全国尺度的大规模边界补全; 3)提供完整的Python+ArcGIS实现方案。该系统为景区精细化管理提供了技术支撑,具有实用价值。

huanghm88的专栏 284

Android 10.0 任务栏音乐播放器后台播放杀进程功能实现

在10.0的系统rom定制化开发过程中,在某些情况下在安装第三方播放器以后,播放音乐的时候,在最近任务栏recents列表中,点击全部清除,发现音乐播放器还在播放音乐,导致出现bug,完整的 解决方法,肯定是需要点击全部清除以后,音乐播放器也被杀掉进程,接下来看下这个问题怎么解决

安卓兼职framework和app工程师的博客 652

侯捷C++手把手教学个人笔记(更新中)

C++ P4 参数传递与返回值 Singleton 构造函数可以定义为private Class中的函数不改变private中的数据的加const 创建const对象,再调用对象中的函数,函数需要是const,否则与创建的const对象矛盾 参数传递: Pass by value vs pass by reference(to const): pass by value可能value占用内存过大所...

weixin_42388228的博客 997

Java全栈开发:充电桩管理系统项目实战

技术收获深入理解分布式系统架构掌握高并发场景解决方案提升系统设计能力经验教训前期需求分析的重要性技术选型需要考虑长期维护测试覆盖率的重要性未来展望引入AI预测故障支持更多支付方式优化用户体验通过此项目的开发,不仅实现了充电桩的智能化管理,也积累了宝贵的全栈开发经验。项目中的很多技术方案和架构设计都具有普遍适用性,可以在其他类似项目中借鉴使用。@Componentstatic {// 初始化状态转换规则。

exlink2012的专栏 1253

侯捷-C++面向对象高级开发-上

侯捷老师经典课程《C++ 面向对象高级开发(上)》的个人学习笔记

weixin_56148345的博客 309

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

设计模式之美——多组合少继承

组合优于继承,多用组合少用继承。

iblade的博客 1218

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Java中的委托和继承(Delegation and Inheritance)

写在前面 概念 Delegation(委托) Dependency: 临时性的delegation Association: 永久性的delegation Composition: 更强的delegation Aggregation Composition vs. Aggregation Inheritance(继承) 各自特点 总结 写在前面 上课的时候对delega...

黑白沙漠 1万+

composition与delegation

将黄色部分简化得到如下: 下面这个是真的有智慧,可以切换不同的版本。只需另外一个版本实现我所需要的接口,随便你怎么折腾。

FairLikeSnow的博客 234

复合Composition 笔记----C++学习之路

1.Composition 复合,可以表示has-a。一个class中有一个另外一种东西。这个class与另外一个东西就叫做复合。 复合关系尽量用图来表示会更加明白。 template class queue { ... protected: deque c; public: bool empty() const { return c.empty(); } si

qq_29003347的博客 1294

面向对象编程的3种关系:组合,委托和继承

看了侯捷老师一节课的视频,做一个记录和小结,在OOP语言中,面向对象编程,类和类之间有3种关系: 1)Inheritance(继承) 2)Composition(复合) 3)Delegation(委托) 先从Compositon开始讲起,其实在C语言中也见到过,一个结构体里面包含另外一个结构体,在C++中复合也是一样的,侯捷老师以标准库来形象的说明了这种情况,在queue类中包含了dequ

cbf9526的博客 5325

GeekBand c++學習筆記之三(面向對象三把刀-inheritece,composition,delegation)

hello,大家好,我又來了,這次要跟大家分享的是,關於C++中一個很大的主題也是C++中一個很重要的功能,就是面向對向的幾個方式,我們就把他歸類為三種,分別是inheritance(繼承)、composition(複合)、delegation(委託),這三種方式大概就可以把整個面向對象整理下來,因為萬變不離其宗,在總麼複雜的程序也是有這三把大刀所組成的,所以懂了最根本的東西,就可以千變萬化的利用

ak47skyang的博客 389

委托Delegation 笔记----C++学习之路

1.委托的概念: 委托和复合非常相似,也是一个类含有has-a一个东西,但是这种拥有很虚,我们不知道何时才会拥有。只在我想 要用到这个东西的时候才去调用,这是与复合的不同。委托的另外一个术语就很明了:Compositon by reference 含有指针的复合,为什么不是by point,因为约定俗成,就是by reference。 举个例子: class StringRep; cla

qq_29003347的博客 804

软件构造之抽象相关知识总结

抽象 1.抽象的概念 基础概念:从众多的事物中抽取出来的共同的、本质的特征,而舍弃其非本质特征的过程。 重点在于 共同 本质 特征 2.抽象方法和抽象类 (1)抽象方法:如果父类当中的方法不确定如何进行{}方法体的实现,那么这个就应该是一个抽象方法。格式:在返回值前加上abstrct关键字,然后去掉大括号(也就是不包括方法体),直接以分号结束。 例如:现在有一个父类(动物),定义一个吃东西的方法,在子类(狗、猫)中定义吃东西的方法,有具体的表现(狗吃骨头,猫吃鱼)。可以看出父类中是无法具体定义方法体

Mr____DAI的博客 1050

[Boolan] C++第三周 类的关系。 复合,委托,继承

1. Composition复合has a的关系,表示一个类是另一个类的成员变量,一个类包含另一个类 class A; class B { public: B(){} ~B(){} private: A a; int b; };构造与析构构造-由内而外:B的构造函数会首先调用A的默认构造函数(编译器自己调用,如果需要传递参数,需要在初始化列表显示调用),然后在调用自

a312024054的专栏 1218

设计模式之美笔记三

设计模式之美笔记三 本文极客时间课程设计模式之美的个人阅读笔记,有不尽详细之处请抱歉,文未可以订阅极客时间该课程。 多用组合少用继承 贫血模型 接口鉴权 如何进行面向对象设计 UML 多用组合少用继承 继承层次过深、过复杂,也会影响到代码的可维护性。 最小知识原则(Least Knowledge Principle,也叫最少知识原则或者迪米特法则),暴露不该暴露的接口给外部,增加了类使用过程中被误用的概率。 组合(composition)、接口、委托(delegation) 一些设计模.

碧海潮生 250
下一篇: 数据库范式
fantasylu
博客等级 码龄24年 0粉丝 4原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值