设计模式是咱们Android成长之路必备的一项技能,相信不少同窗都已经Get了,如今让咱们来看看在Kotlin中设计模式是如何表达的呢。java
单例模式是一种经常使用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。经过单例模式能够保证系统中一个类只有一个实例 。
使用场景: 确保某个类有且只有一个对象的场景,避免产生多个对象消耗过多的资源。设计模式
public class Singleton{
private volatile static Singleton sInstance;
private Singleton() {}
public static Singleton getInstance() {
if (sInstance == null) {
synchronized (Singleton.class) {
if (sInstance == null) {
sInstance = new Singleton();
}
}
}
return sInstance;
}
}
复制代码
饿汉式:安全
public class Singleton {
public static Singleton getInstance() {
return SingletonInstance.sInstance;
}
private static class SingletonInstance {
private static final Singleton sInstance = new Singleton();
}
}
复制代码
object Singleton {
}
复制代码
kotlin写法是否是简单直接越看越喜欢,一句话就归纳了。
来看一下官方的说明bash
Singleton may be useful in several cases, and Kotlin (after Scala) makes it easy to declare singletons, This is called an object declaration, and it always has a name following the object keyword.Object declaration's initialization is thread-safe.app
在 Kotlin 当中直接经过关键字 object 声明一个单例,而且它是线程安全的,而且object 声明的方式也是延迟加载的。ide
代理模式是为其余对象提供一种代理以控制对这个对象的访问学习
代理模式是使用一个代理对象来访问目标对象的行为,Kotlin 下的实现与 Java 基本相似ui
抽象类this
abstract class Notify(var context: Context) {
var notificationManager: NotificationManager? = null
var builder: NotificationCompat.Builder? = null
init {
notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager
builder = NotificationCompat.Builder(context)
builder?.apply {
setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(PendingIntent.getActivity(context, 0,
Intent(context, NotifyActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT))
}
}
/**
* 发送一条通知
*/
abstract fun send()
/**
* 取消一条通知
*/
abstract fun cancel()
}
复制代码
被代理类spa
class NotifyNormal(context: Context) : Notify(context) {
override fun send() {
builder?.let {
it.setContent(RemoteViews(context.packageName, R.layout.layout_notify_normal))
val notification = it.build()
notificationManager?.notify(0, notification)
}
}
override fun cancel() {
notificationManager?.cancel(0)
}
}
复制代码
class NotifyBig(context: Context) : Notify(context) {
override fun send() {
builder?.let {
it.setContent(RemoteViews(context.packageName, R.layout.layout_notify_normal))
it.setCustomBigContentView(RemoteViews(context.packageName, R.layout.layout_notify_normal))
val notification = it.build()
notificationManager?.notify(0, notification)
}
}
override fun cancel() {
notificationManager?.cancel(0)
}
}
复制代码
class NotifyHeadersUp(context: Context) : Notify(context) {
override fun send() {
builder?.let {
it.setContent(RemoteViews(context.packageName, R.layout.layout_notify_normal))
it.setCustomBigContentView(RemoteViews(context.packageName, R.layout.layout_notify_normal))
it.setCustomHeadsUpContentView(RemoteViews(context.packageName, R.layout.layout_notify_normal))
val notification = it.build()
notificationManager?.notify(0, notification)
}
}
override fun cancel() {
notificationManager?.cancel(0)
}
}
复制代码
代理类
class NotifyProxy(context: Context) : Notify(context) {
private var notify: Notify? = null
init {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notify = NotifyHeadersUp(context)
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
notify = NotifyBig(context)
} else {
notify = NotifyNormal(context)
}
}
override fun send() {
notify?.send()
}
override fun cancel() {
notify?.cancel()
}
}
复制代码
调用
NotifyProxy(this@MainActivity).send()
复制代码
经过代理模式能够把复杂的判断和生成通知的逻辑都屏蔽了,让代码更加清晰
建造者模式是将一个复杂对象的构建和它的表示分离,使得一样的构建过程能够建立不一样的表示
好比咱们经常使用的 AlertDialog 、universal-image-loader就是使用的建造者模式,让咱们看看kotlin中该怎么表达
class Dog private constructor(builder: Builder) {
internal var name: String? = null
init {
name = builder.name
}
class Builder {
internal var name: String? = null
fun name(name1: String): Builder {
name = name1
return this
}
fun build(): Dog {
return Dog(this)
}
}
}
复制代码
使用方法与Java同样
Dog.Builder().name("旺财").build()
复制代码
其实Kotlin 的 apply 扩展原生也支持 Builder 模式
class Cat {
var name: String = "miaomiao"
var age = 0
}
复制代码
Cat().apply {
name = "momo"
age = 1
}
复制代码
观察者模式是定义对象间的一种一对多的依赖关系,使得每当一个对象改变状态,则全部依赖于它的对象都会获得通知并被自动更新
常见的观察者模式如RecyclerView的Adapter的notifyDataSetChanged更新方法、BroadcastReceiver、开源库EventBus、RxJava等等
Kotlin的写法与Java相似
经过UnReadMessageObserver 单例来实现全局观察管理未读消息
object UnReadMessageObserver {
private var map = mutableMapOf<String, UnReadMessageListener>()
fun addUnReadMessageListener(listenerKey: String, listener: UnReadMessageListener) {
map[listenerKey] = listener
}
fun updateUnReadMessage(count: Int) {
map.forEach {
it.value.updataUnReadMessage(count)
}
}
fun removeUnReadMessageListener(listenerKey: String) {
if (map.containsKey(listenerKey)) {
map.remove(listenerKey)
}
}
}
interface UnReadMessageListener {
fun updataUnReadMessage(unReadCount: Int)
}
复制代码
被观察者
UnReadMessageObserver.updateUnReadMessage(1)
复制代码
观察者
UnReadMessageObserver.addUnReadMessageListener(MainActivity::class.java.name, object : UnReadMessageListener {
override fun updataUnReadMessage(unReadCount: Int) {
Toast.makeText(this@MainActivity, "count:$unReadCount", Toast.LENGTH_SHORT).show()
}
})
复制代码
观察者模式是咱们常常使用的模式,它的一个重要做用就是解耦,将观察者个被观察者解耦
适配器模式把一种接口变换成客户端所期待的另外一种接口,从而使本来因接口不匹配而没法在一块儿工做的两个类可以在一块儿工做
举个栗子:手机普通充电须要5V的电压,而生活用电电压是220V,而咱们的充电器就充当了转换适配的做用,
这里的适配器也是一个道理
适配器模式中的目标接口也就是 5V电压的接口
interface VoltageFive {
fun Voltage5(): Int
}
复制代码
适配器模式中须要被适配的接口,平常220V电压
class VoltageDaily {
fun Voltage220(): Int {
return 220
}
}
复制代码
适配器
class VoltageAdapter(var voltageDaily: VoltageDaily) : VoltageFive {
override fun Voltage5(): Int {
return 5
}
fun getVoltage220(): Int {
return voltageDaily.Voltage220()
}
}
复制代码
以上就是适配器模式在Kotlin上的简单实现了,适配器模式的原理在于把本来不兼容的接口融合在了一块儿,使之能更好的协做。
以上几种设计模式是咱们常常会用到的,Kotlin的大多设计模式基本与Java实现大体相同,灵活的使用设计模式能让咱们代码更加的灵活,便于管理。本次学习就到这了,同窗们下次再见。