[英]update the state of component from another component
I have a class 我有一堂课
class TableComponent {
tableBody
tableHeader
tableFooter
}
TableHeader
has a button that should be enabled or disabled depending on the state of tableBody
TableHeader
有一个按钮,应根据tableBody
的状态启用或禁用
class TableHeader {
button
void enableButton(false|true)
}
To handle this I pass instance of TableHeader
to TableBody
like this 为了解决这个问题我通过实例TableHeader
到TableBody
这样
new TableBody(tableHeader);
and inside the tableBody
I do some actions and invoke tableHeader.enableButton()
在tableBody
内部,我执行一些操作并调用tableHeader.enableButton()
But is there a way not to pass the reference of tableHeader
into the body? 但是,有没有一种方法可以不将tableHeader
的引用传递给主体呢? Would use for example of EventBus
better? 例如使用EventBus
更好吗? Or for join all table classes into a single class? 还是将所有表类都合并为一个类?
You're very close to the Observer Pattern already. 您已经非常接近观察者模式。 The missing piece is just to create the Pub/Sub interfaces, so that when you pass the header into the body, you have a layer of abstraction in place that prevents concrete table components from coupling to each other directly. 缺少的部分只是创建Pub / Sub接口,以便在将标头传递到主体时,具有适当的抽象层,可以防止具体的表组件直接相互耦合。
public class MainJava {
interface Publisher { void subscribe(Subscriber s); }
interface Subscriber { void update(); }
public static void main(String... args) {
TableComponent component = new TableComponent(new TableBody(), new TableHeader(), new TableFooter());
component.setBodyText("Hello World");
}
static class TableComponent {
final TableBody body;
final TableHeader header;
final TableFooter footer;
public TableComponent(TableBody body, TableHeader header, TableFooter footer) {
this.body = body;
this.header = header;
this.footer = footer;
body.subscribe(header);
}
public void setBodyText(String newBody) {
body.edit(newBody);
}
}
static class TableBody implements Publisher {
final Set<Subscriber> subscribers = ConcurrentHashMap.newKeySet();
@Override
public void subscribe(Subscriber s) {
subscribers.add(s);
}
void edit(String newBody) {
System.out.println(newBody);
subscribers.forEach(Subscriber::update);
}
}
static class TableHeader implements Subscriber {
@Override
public void update() {
System.out.println("Toggle Button");
}
}
static class TableFooter {}
}
Although the line body.subscribe(header);
尽管行body.subscribe(header);
may appear no different from new TableBody(tableHeader);
可能看起来与new TableBody(tableHeader);
没有什么不同new TableBody(tableHeader);
it's critical in the former that body
sees header
only as a Subscriber
whereas in the latter body
is aware that header
is a TableHeader
. 它是在前者的关键是body
看到header
仅作为Subscriber
,而在后者body
意识到, header
是TableHeader
。 That layer of abstraction is the difference between tight coupling and loose coupling. 那个抽象层是紧密耦合和松散耦合之间的区别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.