如何构造两个对象,彼此作为参数/成员 [英] How to construct two objects, with each other as a parameter/member

查看:64
本文介绍了如何构造两个对象,彼此作为参数/成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类,每个类都需要一个彼此的实例才能起作用.通常,如果一个对象需要另一个对象来运行,我喜欢在构造函数中传递它.但是在这种情况下我不能这样做,因为一个对象必须在另一个对象之前实例化,因此第二个对象不存在才能传递给第一个对象的构造函数.

I have two classes that each need an instance of each other to function. Ordinarily if an object needs another object to run, I like to pass it in the constructor. But I can't do that in this case, because one object has to be instantiated before the other, and so therefore the second object does not exist to be passed to the first object's constructor.

我可以通过以下方式解决此问题:将第一个对象传递给第二个对象的构造函数,然后在第一个对象上调用setter将第二个对象传递给它,但这似乎有些笨拙,我想知道是否还有更好的方法方式:

I can resolve this by passing the first object to the second object's constructor, then calling a setter on the first object to pass the second object to it, but that seems a little clunky, and I'm wondering if there's a better way:

backend = new Backend();
panel = new Panel(backend);
backend.setPanel();

我从未对MVC进行过任何研究;我想在这里处理一个模型(后端),以及一个视图或控制器(面板).我可以从MVC中获得任何见解?

I've never put any study into MVC; I suppose I'm dealing with a model here (the Backend), and a view or a controller (the Panel). Any insights here I can gain from MVC?

推荐答案

是时候看看MVC了. :-)当您遇到模型-视图-控制器的情况时,共识是模型不应该知道视图-控制器(MVC通常扮演M-VC的角色),但是视图始终知道模型

It's time to take a look at MVC. :-) When you have a model-view-controller situation, the consensus is that the model shouldn't be aware of the view-controller (MVC often plays out as M-VC), but the view is invariably aware of the model.

如果模型需要告知视图某些内容,则通过通知其侦听器(可能有多个侦听器)来做到这一点.您的视图应该是其中之一.

If the model needs to tell the view something, it does so by notifying its listeners, of which it may have multiples. Your view should be one of them.

这篇关于如何构造两个对象,彼此作为参数/成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆