假设有您需要实现业务功能,这台某种轮廓。简单的继承
根据数据如何接收,但可以设置个人资料将被不同的方式实现。
例如参数可以直接传递给将能够
setProfile();
或对象,参数必须被发现,并就必须通过由
setProfile(String[] data, Blah blooh);
个人资料在这种情况下最好的方法是什么?我的意思是,设计明智你将如何构建这个?
我想使用接口与抽象方法,它的工作原理,但引入了一些噪音。不确定如何最好地构造这个。
假设有您需要实现业务功能,这台某种轮廓。简单的继承
根据数据如何接收,但可以设置个人资料将被不同的方式实现。
例如参数可以直接传递给将能够
setProfile();
或对象,参数必须被发现,并就必须通过由
setProfile(String[] data, Blah blooh);
个人资料在这种情况下最好的方法是什么?我的意思是,设计明智你将如何构建这个?
我想使用接口与抽象方法,它的工作原理,但引入了一些噪音。不确定如何最好地构造这个。
我会通过抽象的实际轮廓,以自己的类层次结构封装,并添加泛型到setProfile()
去。当然,它确实增加了一些复杂性,但是因为它也引入了间接性,所以代码将更加分离,从长远来看应该证明是有用的。
此外,实际的功能也可能在其自己的类层次结构中,从而使该部分可插入,这意味着您的手中会有Strategy Pattern。然而,应用这个决定需要更多关于你正在构建的系统的知识,并且可能不适合你正在构建的系统。
快速例如:
/**
* Interface for describing the actual function. May (and most likely does)
* contain other methods too.
*/
public interface BusinessFunction<P extends Profile> {
public void setProfile(P p);
}
/**
* Base profile interface, contains all common profile related methods.
*/
public interface Profile {}
/**
* This interface is mostly a matter of taste, I added this just to show the
* extendability.
*/
public interface SimpleProfile extends Profile {}
/**
* This would be what you're interested of.
*/
public interface ComplexProfile extends Profile {
String[] getData();
Blah blooh();
}
/**
* Actual function.
*/
public class ComplexBusinessFunction implements BusinessFunction<ComplexProfile> {
public void setProfile(ComplexProfile p) {
// do whatever with p which has getData() and blooh()
}
}
/**
* And another example just to be thorough.
*/
public class SimpleBusinessFunction implements BusinessFunction<SimpleProfile> {
public void setProfile(SimpleProfile p) {
// do whatever with the empty profile
}
}
我总是很紧张周围有许多重载方法。我比较喜欢,在这种情况下,想方法参数的消息,而不是参数,并建立一个单一的方法,像这样:
setProfile(ProfileData data)
的ProfileData
类可以包含在所有的你setProfile
办法制定共同的数据,并且可以为专门的setProfile
操作创建派生类。
这种方法如果使用的是序列化技术,可以自动地坚持基于其结构中的ProfileData
对象时特别有用。
对于get/set方法,我始终保持在设定的方法作为一个单一的输入。不要只是一个简单的对象,可能是一个更复杂的对象,正如kbirmington所建议的那样。我认为我比其他任何真正的设计优势都要做得更好。
它值得记住不过,如果配置文件数据有10个属性,他们只提供9折他们,有可能你会写在此基础上的10个属性,实际上是缺少9种不同的方法。
至少具有单一结构中,存在一个输入,而且如果结构改变方法确实里面不仅该代码。
在这方面你是编程到这是一个很好的设计模式的界面。
爱它。谢谢 – JAM 2010-08-28 16:12:28