什么是装饰设计模式
装饰设计模式通过组合而非继承的方式,来动态地扩展对象功能。
具体点,就是通过一个(装饰)类包裹真实对象(装饰对象和真实对象实现了同一份接口),在转发真实对象请求的前后,增加代码实现功能增强。
这种设计无需修改原有的类,很好地遵循了“开闭原则”。
接下来,我们就通过一个简单的例子来快速了解它。
入门示例:给咖啡动态加料
比如有一杯普通咖啡:
interface Coffee {
val description: String
val price: Int
}
class BasicCoffee : Coffee {
override val description = "Basic coffee"
override val price = 12
}
如果要新增拿铁,我们一般会这么做:
class LatteCoffee : Coffee {
override val description = "Basic coffee + Milk"
override val price = 15
}
但如果后续配料越来越多,比如还要加冰块、加糖,这种写法会导致类迅速膨胀。
引入装饰设计模式后,我们可以直接包裹 Coffee 对象,在转发方法时增强原有的行为:
class MilkDecorator(private val coffee: Coffee) : Coffee {
override val description get() = "${coffee.description} + Milk"
override val price get() = coffee.price + 3
}
class SugarDecorator(private val coffee: Coffee) : Coffee {
override val description get() = "${coffee.description} + Sugar"
override val price get() = coffee.price + 1
}
调用示例:
class MainActivity : AppCompatActivity() {
private lateinit var milkCheckBox: CheckBox
private lateinit var sugarCheckBox: CheckBox
private lateinit var resultText: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
milkCheckBox = findViewById(R.id.milkCheckBox)
sugarCheckBox = findViewById(R.id.sugarCheckBox)
resultText = findViewById(R.id.resultText)
milkCheckBox.setOnCheckedChangeListener { _, _ -> updateOrder() }
sugarCheckBox.setOnCheckedChangeListener { _, _ -> updateOrder() }
updateOrder()
}
private fun updateOrder() {
var coffee: Coffee = BasicCoffee()
if (milkCheckBox.isChecked) {
coffee = MilkDecorator(coffee)
}
if (sugarCheckBox.isChecked) {
coffee = SugarDecorator(coffee)
}
resultText.text = "Coffee result: ${coffee.description}, Price: ${coffee.price}\n"
}
}
点击展开布局文件(activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical"
android:padding="24dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Decorator Pattern Example"
android:textSize="24sp"
android:textStyle="bold" />
<CheckBox
android:id="@+id/milkCheckBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="Add milk" />
<CheckBox
android:id="@+id/sugarCheckBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add sugar" />
<TextView
android:id="@+id/resultText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:textSize="18sp" />
</LinearLayout>
运行结果:
不仅可以轻松扩展功能,而且还能叠加实现,比如同时勾选了 “Add milk” 和 “Add sugar”,价格会从基础的 12 变为 16(+3、+1),描述最终也会变为 “Basic coffee + Milk + Sugar”。
Android 实战:可扩展的图片加载器
接下来我们以图片加载作为实战场景,先完成根据输入的 URL,在界面中显示一张图片,后续在这个基础上逐层包装,实现内存缓存和请求失败显示兜底图片的功能。
基础实现:网络下载图片
因为涉及到网络请求,先在清单文件中加上网络访问权限:
<uses-permission android:name="android.permission.INTERNET" />
然后定义 ImageLoader 接口,并实现从网络下载图片、将返回的输入流解码成 Bitmap 的基础加载类:
interface ImageLoader {
suspend fun load(url: String): Bitmap
}
class NetworkImageLoader : ImageLoader {
override suspend fun load(url: String): Bitmap = withContext(Dispatchers.IO) {
val normalizedUrl = url.trim()
require(isValidUrl(normalizedUrl)) {
"Please enter a valid URL."
}
val requestUrl = URL(normalizedUrl)
val connection = (requestUrl.openConnection() as HttpURLConnection).apply {
connectTimeout = 10_000
readTimeout = 15_000
instanceFollowRedirects = true
}
try {
val responseCode = connection.responseCode
if (responseCode !in 200..299) {
throw IOException("Server returned HTTP $responseCode.")
}
return@withContext connection.inputStream.use { input ->
BitmapFactory.decodeStream(input)
?: throw IOException("The response is not a valid image.")
}
} finally {
connection.disconnect()
}
}
private fun isValidUrl(url: String): Boolean {
return url.trim().let { normalizedUrl ->
normalizedUrl.startsWith("http://") || normalizedUrl.startsWith("https://")
}
}
}
在 MainActivity 中创建 ImageLoader,并调用:
private val imageLoader: ImageLoader by lazy {
NetworkImageLoader()
}
val bitmap = imageLoader.load(url)
imageView.setImageBitmap(bitmap)
点击展开完整 MainActivity 代码
class MainActivity : AppCompatActivity() {
//region Views
private lateinit var binding: ActivityMainBinding
private lateinit var urlInput: TextInputEditText
private lateinit var loadButton: MaterialButton
private lateinit var progressBar: ProgressBar
private lateinit var statusText: TextView
private lateinit var imageView: ImageView
//endregion
//region load Image
private val imageLoader: ImageLoader by lazy {
NetworkImageLoader()
}
private var loadJob: Job? = null
//endregion
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
initViews()
initListeners()
}
private fun initViews() {
urlInput = binding.urlInput
loadButton = binding.loadButton
progressBar = binding.progressBar
statusText = binding.statusText
imageView = binding.imageView
}
private fun initListeners() {
loadButton.setOnClickListener {
loadImage()
}
urlInput.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_GO) {
loadImage()
true
} else {
false
}
}
}
private fun loadImage() {
val url = urlInput.text?.toString()?.trim().orEmpty()
if (url.isEmpty()) {
statusText.text = "Please enter an image URL."
return
}
loadJob?.cancel()
imageView.setImageDrawable(null)
progressBar.visibility = ProgressBar.VISIBLE
loadButton.isEnabled = false
statusText.text = "Loading..."
loadJob = lifecycleScope.launch {
val startTime = SystemClock.elapsedRealtime()
try {
val bitmap = imageLoader.load(url)
imageView.setImageBitmap(bitmap)
val elapsedTime = SystemClock.elapsedRealtime() - startTime
statusText.text =
"Load finished in ${elapsedTime}ms."
} catch (error: CancellationException) {
throw error
} catch (error: Exception) {
statusText.text = "Load failed: ${error.message}"
} finally {
progressBar.visibility = ProgressBar.GONE
loadButton.isEnabled = true
}
}
}
}
点击展开布局文件(activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Image Loader Decorators"
android:textSize="26sp"
android:textStyle="bold" />
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.Material3.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Image URL">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/urlInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionGo"
android:inputType="textUri"
android:maxLines="1"
android:text="https://picsum.photos/id/1015/800/600.jpg" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.button.MaterialButton
android:id="@+id/loadButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="Load Image" />
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="4dp"
android:layout_marginTop="12dp"
android:indeterminate="true"
android:visibility="gone" />
<TextView
android:id="@+id/statusText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="Ready"
android:textSize="16sp" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="320dp"
android:layout_marginTop="16dp"
android:background="#EEF1F4"
android:contentDescription="Loaded image"
android:scaleType="centerCrop" />
</LinearLayout>
</ScrollView>
运行效果:
功能增强一:添加内存缓存
接下来对加载过的图片进行缓存,创建 MemoryCacheImageLoader 来包裹原有的 ImageLoader 对象:
class MemoryCacheImageLoader(
private val delegate: ImageLoader
) : ImageLoader {
/** 内存键值缓存,会自动淘汰最近最少使用的数据(LRU) */
private val cache = object : LruCache<String, Bitmap>(
(Runtime.getRuntime().maxMemory() / 1024 / 8).toInt()
) {
/** 每个 Bitmap 占用的内存(KB),至少为 1 防止极小图片触发异常 */
override fun sizeOf(key: String, value: Bitmap): Int {
return (value.byteCount / 1024).coerceAtLeast(1)
}
}
override suspend fun load(url: String): Bitmap {
val cacheKey = url.trim()
cache.get(cacheKey)?.let { bitmap ->
Log.d(TAG, "Memory cache hit: $cacheKey")
return bitmap
}
Log.d(TAG, "Memory cache miss: $cacheKey")
return delegate.load(cacheKey).also { bitmap ->
cache.put(cacheKey, bitmap)
}
}
private companion object {
const val TAG = "ImageLoader"
}
}
在调用处,只需用 MemoryCacheImageLoader 包裹 NetworkImageLoader() 对象即可,其余代码无需改动:
private val imageLoader: ImageLoader by lazy {
MemoryCacheImageLoader(NetworkImageLoader())
}
感觉到开闭原则的强大了吧,原有的调用代码一行都不用动,套一层就拥有了缓存能力。
运行效果:
第二次加载图片时,直接命中缓存,耗时非常低。
功能增强二:异常兜底
最后,再来完成加载图片出现异常时,使用指定的图片进行兜底:
class FallbackImageLoader(
private val delegate: ImageLoader,
private val fallbackBitmap: Bitmap
) : ImageLoader {
override suspend fun load(url: String): Bitmap {
return try {
delegate.load(url)
} catch (error: CancellationException) {
throw error
} catch (error: Exception) {
Log.w(TAG, "Image load failed, using fallback: $url", error)
fallbackBitmap
}
}
private companion object {
const val TAG = "ImageLoader"
}
}
兜底图直接使用 Canvas 进行绘制:
private fun createFallbackBitmap(): Bitmap {
val bitmap = createBitmap(800, 600)
val canvas = Canvas(bitmap)
canvas.drawColor(Color.rgb(238, 241, 244))
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.rgb(134, 144, 156)
textSize = 48f
textAlign = Paint.Align.CENTER
}
canvas.drawText(
"IMAGE LOAD FAILED",
bitmap.width / 2f,
bitmap.height / 2f - (paint.ascent() + paint.descent()) / 2f,
paint
)
return bitmap
}
再次进行组装:
private val fallbackBitmap: Bitmap by lazy {
createFallbackBitmap()
}
private val imageLoader: ImageLoader by lazy {
FallbackImageLoader(
MemoryCacheImageLoader(NetworkImageLoader()),
fallbackBitmap
)
}
故意输入一个错误的 URL 进行验证:
最后有一个小细节,包裹的顺序非常重要。
FallbackImageLoader 必须放在 MemoryCacheImageLoader 的外层。如果放在内层,就会出现加载失败时的兜底图被缓存到 LruCache 中的情况,导致后续请求都会直接命中错误的兜底图。
小结
在实际开发中,装饰模式非常常见,比如 Java IO 中的 BufferedInputStream(FileInputStream(...)),以及 Android 里的 ContextWrapper(内部包裹了真正的 ContextImpl),都是典型的包装扩展实例。
另外,装饰器的结构和代理模式非常相似,但二者的重点不同:
装饰模式强调动态叠加职责,通常由调用方自由进行组合;而代理模式侧重于控制对真实对象的访问,往往会对调用方隐藏底层的真实对象。
总的来说,装饰模式能灵活地扩展功能,但是要适当使用,否则调用链路过深会影响问题排查,而且还要注意嵌套的顺序。