Java 如何根据给定的主题类型初始化复杂对象模型的属性?
我有复杂的对象模型(涉及很多继承/组合)。它的某些属性符合主题的一部分。 给定一个主题,我想初始化它的各种属性 我应该如何设计一个通用的主题类Java 如何根据给定的主题类型初始化复杂对象模型的属性?,java,oop,design-patterns,Java,Oop,Design Patterns,我有复杂的对象模型(涉及很多继承/组合)。它的某些属性符合主题的一部分。 给定一个主题,我想初始化它的各种属性 我应该如何设计一个通用的主题类 是否有任何设计模式支持此功能?对我来说,主题听起来像是一组视觉属性,如字体大小、背景颜色等。您的复杂对象模型听起来几乎像是一个控件/UI元素层次结构,其中每个控件/元素都有您希望主题类初始化的属性 您需要做的是使复杂对象模型中的每个对象都具有主题性,因此我们创建了IThemeable: interface IThemeable { void U
是否有任何设计模式支持此功能?对我来说,主题听起来像是一组视觉属性,如字体大小、背景颜色等。您的复杂对象模型听起来几乎像是一个控件/UI元素层次结构,其中每个控件/元素都有您希望主题类初始化的属性 您需要做的是使复杂对象模型中的每个对象都具有主题性,因此我们创建了IThemeable:
interface IThemeable
{
void UpdateThemeableProperties();
}
为了使UpdateThemeableProperties()更有意义,让我们在一个复杂对象中实现它
class AComplexObject implements IThemable
{
public bool Selected; // a primitive property we want themeble
public AnotherComplexObject anotherComplexObject; // implements IThemeable
public List<IThemable> Children;
// your object may have other themeable and non-themeable properties.
public AComplexObject()
{
Children = new List<IThemable>();
UpdateThemableProperties();
}
public void UpdateThemableProperties()
{
if (App.CurrentTheme != null)
{
// take care of your primitive properties first by practice
object valueFromTheme = App.CurrentTheme.getPropertyValue("AComplexObject,"Selected");
Selected = (valueFromTheme != null) ? valueFromTheme : false;
// false would be the default value if the theme didn't provide it.
// Do the same as above for all primitive properties you want to
// participate in the theme.
// Do for each individual complex property
if(anotherComplexObject != null)
{
anotherComplexObject.UpdateThemeableProperties();
}
// Do for each of your lists of complex objects:
for each (IThemable it in Children)
{
it.UpdateThemeableProperties();
}
}
}
}
那是一个相当长的帖子。总之
- 复杂对象模型中具有主题的每个类 属性必须实现IThemeable
- 记住实现每个IThemeable类的UpdateThemeableProperties()。在尝试从当前主题获取属性值之前,您需要知道哪些属性可设置主题
- 在更改当前主题、在列表中添加IThemeable项以及实例化实现IThemeable的类型的属性时,在IThemeable类的构造函数中调用UpdateThemeableProperties()
class CurrentTheme
{
private Dictionary<String,Object> values;
public CurrentTheme()
{
values = new Dictionary<String,Object>();
}
public void setPropertyValue(string className, string propertyName, Object value)
{
values.add(className + "_" + propertyName, value);
}
public Object getPropertyValue(string className, string propertyName)
{
if (values.keyExists(className + "_" + propertyName)
{
return values[className + "_" + propertyName];
}
else
{
return null;
}
}
}
public addChild(SomeComplexObjectThatImplementsIThemeable child)
{
Children.add(child);
child.UpdateThemeableProperties();
}