【抽象工厂模式定义】:
为创建一组相关或者是相互依赖的对象提供一个接口,而不需要指定它们的具体类。
【抽象工厂的使用场景】:
一个对象族有相同的约束时可以使用抽象工厂模式。是不是听起来很抽象?举个例子,Android、IOS、WindowPhone下都有短信软件和拨号软件,两者都属于软件的范畴,但是,它们所在的操作系统平台不一样,即使是同一家公司出口的软件,其代码的实现逻辑也是不同的,这时候就可以考虑使用抽象工厂方法模式来产生Android、iOS、Window Phone下的短信软件和拨号软件。
【抽象工厂模式在Android开发中的应用】:
抽象工厂类:
抽象主题工厂类:
public abstract class AbstractThemeFactory {
protected Context context;
public AbstractThemeFactory(Context context) {
this.context = context;
}
/**
* 创建主题按钮
* return 主题按钮
* /
public abstract ThemeButton createButton();
/**
* 创建主题标题栏
* @return 主题标题栏
* /
public abstract ThemToolbar createToolbar();
}
具体工厂类:
暗色系主题工厂类:
public class DarkThemeFactory extends AbstractThemeFactory {
publict DarkThemeFactory(Context context) {
super(context);
}
@Override
public ThemeButton createButton() {
return new ButtonDark(context);
}
@Override
public ThemeToolbar createToolbar() {
return new ToolbarDark(context);
}
}
亮色系主题工厂类:
public class LightThemeFactory extends AbstractThemeFactory {
public LightThemeFactory(Context context) {
super(context);
}
@Override
public ThemeButton createButton() {
return new ButtonLight(context);
}
@Override
public ThemeToolbar createToolbar() {
return new ToolbarLight(context);
}
}
抽象主题类:
抽象主题按钮:
public abstract class ThemeButton extends Button {
public ThemeButton(Context context) {
super(context);
initTextColoer();
initBackgroundColor();
}
/**
* 初始化文本颜色
* /
abstract void initTextColor();
/**
* 初始化背景颜色
* /
abstract void initBarckgroundColor();
}
抽象主题标题类:
public abstract class ThemeToolbar extends Toolbar {
public ThemeToolbar(Context context) {
super(context);
initIcon();
initTextColor();
initBackgroundColor();
}
/**
* 初始化图标
* /
abstract void initIcon();
/**
* 初始化文本颜色
* /
public initTextColor();
/**
* 初始化背景颜色
* /
abstract void initBackgroundColor();
}
具体主题类:
具体暗色主题按钮:
public class ButtonDark extends ThemeButton {
public ButtonDark (Context context) {
super(context);
...
}
void initTextColor(){...}
void initBarckgroundColor(){..}
}
具体亮色主题按钮:
public class ButtonLight extends ThemeButton {
public ButtonLight(Context context) {
super(context);
...
}
void initTextColor(){...}
void initBarckgroundColor(){..}
}
具体暗色主题标题类:
public class ToolbarDark extends ThemeToolbar {
public ToolbarDark(Context context) {
super(context);
...
}
void initIcon(){..}
public initTextColor(){..}
void initBackgroundColor(){..}
}
具体亮色主题标题类:
public class ToolbarLightextends ThemeToolbar {
public ToolbarLight(Context context) {
super(context);
...
}
void initIcon(){..}
public initTextColor(){..}
void initBackgroundColor(){..}
}
总结:
主要分为四大模块:
- 抽象工厂;
- 具体工厂;
- 抽象主题;
- 具体主题。
本文深入解析抽象工厂模式的定义、应用场景及在Android开发中的实践。通过创建一组相关或相互依赖的对象,无需指定具体类,实现不同主题风格的统一管理。
178

被折叠的 条评论
为什么被折叠?



