Sunday, April 01, 2007
Default Interface Implementation
這是AspectJ in Action裡8.5.4 Providing a default interface implementation中的程式碼
With OOP
public interface Nameable {
public void setName(String name);
public String getName();
}
===============================================================================
public interface Identifiable {
public void setId(String id);
public String getId();
}
===============================================================================
public class Entity implements Nameable, Identifiable {
private String _name;
private String _id;
public void setName(String name) {
_name = name;
}
public String getName() {
return _name;
}
public void setId(String id) {
_id = id;
}
public String getId() {
return _id;
}
}
With AOP
public interface Nameable {
public void setName(String name);
public String getName();
static aspect Impl {
private String Nameable._name;
public void Nameable.setName(String name) {
_name = name;
}
public String Nameable.getName() {
return _name;
}
}
}
===============================================================================
public interface Identifiable {
public void setId(String id);
public String getId();
static aspect Impl {
private String Identifiable._id;
public void Identifiable.setId(String id) {
_id = id;
}
public String Identifiable.getId() {
return _id;
}
}
}
===============================================================================
public class Entity implements Nameable, Identifiable {
}
有了AOP後
Default Implementation不再是class與abstract class的專利
看看上面的程式碼
想想自己系統中多少domain object有name與id這兩個property
就會知道這個AOP Idiom可以省下多少行程式
不過設計上要更小心是一定的
另外AJDT對於這些introduction進來的field與method
似乎還沒有辦法用快捷鍵則是比較麻煩的地方