【发布时间】:2010-06-28 14:22:42
【问题描述】:
在等待question 上的答案的同时,我想讨论可能的实施计划/细节,或者一般来说甚至回答实施以下内容的难度以及为此需要哪些工具/技术:
(摘自所提问题):
假设您需要实现许多 (子)类型的集合。中的一个 方面是存储相关:列表, array 等,而另一个是 行为相关:有序,移除 only, observable(触发的那个 每次更改时发生的事件)等。
显然(再次),要求 直接映射到众所周知的 装饰器设计模式,其中存储相关 aspect (list, array) 将被多个修饰 行为(有序、可观察等)。
到目前为止,我想在(类 Java)伪代码中提出一些相当短的实现,同时询问是否可以在 Java 或 C# 中实现以下内容,或者,如果不能,则在任何其他现代编程语言中实现:
每个集合必须支持的基本接口:
interface Collection {
[mutator]
public void add(object o);
[mutator]
public void remove(object o);
[accessor]
public object get(int i);
}
存储方面:
列表实现:
class List : Collection {
[mutator]
public void add(object o) { ... }
[mutator]
public void remove(object o) { ... }
[accessor]
public object get(int i) { ... }
}
数组实现:
class Array : Collection {
[mutator]
public void add(object o) { ... }
[mutator]
public void remove(object o) { ... }
[accessor]
public object get(int i) { ... }
}
行为方面:
线程安全装饰器:
typename<T> : where T is Collection
class ThreadSafe : Collection {
private T m_source;
private object m_lock = new object();
[mutator]
public void add(object o) {
using (m_lock) {
m_source.add();
}
}
[mutator]
public void remove(object o) { ... }
[accessor]
public object get(int i) { ... }
}
Observable 装饰器:
class ChangeEvent {
public Collection Source { get; private set; }
public Method UpdateType { get; private set; }
}
interface Observer {
public notifyChange(ChangeEvent e);
}
typename<T> : where T is Collection
class Observable : Collection {
public Observer Observer { get; set; } // additional property
private T m_source;
[mutator]
public void add(object o) {
if (Observer != null) {
var event = new ChangeEvent() { Source = this, UpdateType = GetCurrentMethod() };
Observer.notifyChange(event);
}
m_source.add(o);
}
[mutator]
public void remove(object o) { ... }
[accessor]
public object get(int i) { ... }
}
有序装饰器:
typename<T> : where T is Collection
class Ordered : Collection {
private T m_source;
[mutator]
public void add(object o) {
int idx = findProperPosition(); // assumed possible using the base Collection interface
...
m_source.add(o);
}
[mutator]
public void remove(object o) { ... }
[accessor]
public object get(int i) { ... }
}
只读装饰器:
typename<T> : where T is Collection
class ReadOnly : Collection {
private T m_source;
[mutator]
public void add(object o) { throw IllegalOperationException(...); }
[mutator]
public void remove(object o) { throw IllegalOperationException(...); }
[accessor]
public object get(int i) { return m_source.get(i); }
}
到目前为止,以上只是伪代码,但目标是使客户端代码能够构造多种集合,以便每种集合都可以恰好组合一个存储方面任意数量的行为相关的方面。能够在编译时构造这些复合类型并且超级方便地在运行时生成这些复合类型会非常好。
问题是(任何现代编程语言都算数)?
【问题讨论】:
-
好吧,让我们看看情况如何。 FAQ的前两句“我不应该在这里问什么样的问题?”很好地描述了这个主题。
-
先抱歉。改写了主要(实际)问题。
标签: c# java collections aop