java 設(shè)計模式

  1. 單例模式:確保某一個類只有一個實例,而且自行實例化并向整個系統(tǒng)提供這個實例。
    場景:一些工具類,RetrofitHelper、EventBus等。
public class Singleton { 
 // 注意要加 volatile,保證可見性、有序性 
  private volatile static Singleton instance;
 
  private Singleton() {}
 
  public static Singleton getInstance() {
    if (instance == null) {
      synchronized(Singleton.class) {
        if (instance == null) {
          instance = new Singleton();
        }
      }
    }
    return instance;
  }
  1. 建造者模式:將一個復(fù)雜對象的構(gòu)建與它的表示分離,使得同樣的構(gòu)建過程可以創(chuàng)建不同的展示。
    場景:Dialog、Retrofit、OkHttp等。
 class Person {
    var name: String? = null  //名字
    var age = 0               //年齡
    var height = 0.0          //身高
    var weight = 0.0          //體重

    constructor(builder: Builder) {
        name = builder.name
        age = builder.age
        height = builder.height
        weight = builder.weight
    }

    class Builder {
        var name: String? = null  //名字
        var age = 0               //年齡
        var height = 0.0          //身高
        var weight = 0.0          //體重

        fun setName(name: String?): Builder {
            this.name = name
            return this
        }

        fun setAge(age: Int): Builder {
            this.age = age
            return this
        }

        fun setHeight(height: Double): Builder {
            this.height = height
            return this
        }

        fun setWeight(weight: Double): Builder {
            this.weight = weight
            return this
        }

        fun build(): Person {
            return Person(this)
        }
    }
}
  1. 觀察者模式:定義對象間的一種一對多的依賴關(guān)系,當(dāng)一個對象的狀態(tài)發(fā)送改變時,所有依賴于它的對象都能得到通知并被自動更新。
    場景:EventBus、RxJava等。
// 被觀察者接口
open interface Observable {
    fun addObserver(observer: Observer?)
    fun deleteObserver(observer: Observer?)
    fun notifyObservers(info: String?)
}

// 被觀察者
class LibraryObservable : Observable {
    //觀察者集合
    private val observers: ArrayList<Observer>?

    init {
        observers = ArrayList()
    }

    @Synchronized
    override fun addObserver(observer: Observer?) {
        if (observer == null) {
            throw NullPointerException()
        }
        if (!observers!!.contains(observer)) {
            observers.add(observer)
        }
    }

    @Synchronized
    override fun deleteObserver(observer: Observer?) {
        if (observer == null) {
            throw NullPointerException()
        }
        observers!!.remove(observer)
    }

    override fun notifyObservers(info: String?) {
        if (observers == null || observers.size <= 0) {
            return
        }
        for (observer in observers) {
            observer.update(info)
        }
    }
}

// 觀察者接口
open interface Observer {
    fun update(info: String?)
}

// 觀察者
class StudentObserver : Observer {
    override fun update(info: String?) {
        println(info)
    }
}

fun main() {
    val studentA = StudentObserver()
    val studentB = StudentObserver()
    //被觀察者圖書館
    val library = LibraryObservable()
    //studentA 和 studentB 在圖書館登記
    library.addObserver(studentA)
    library.addObserver(studentB)
    //圖書館有書了通知
    library.notifyObservers("有新書到了!")
}
  1. 責(zé)任鏈設(shè)計模式:責(zé)任鏈模式是一種對象的行為模式。在責(zé)任鏈模式里,很多對象由每一個對象對其下家的引用而連接起來形成一條鏈。請求在這個鏈上傳遞,直到鏈上的某一個對象決定處理此請求。發(fā)出這個請求的客戶端并不知道鏈上的哪一個對象最終處理這個請求,這使得系統(tǒng)可以在不影響客戶端的情況下動態(tài)地重新組織和分配責(zé)任。
    場景:Android事件分發(fā)
// Handler:抽象處理者,聲明一個請求的處理方法
open interface Handler {
    fun handleRequest(name: String?, days: Int)
}

// 責(zé)任鏈類
class HandlerChain : Handler {
    private val handlerList: ArrayList<Handler>

    init {
        handlerList = ArrayList()
    }

    fun addHandler(handler: Handler?): HandlerChain {
        handler?.let{
            handlerList.add(it)
        }
        return this
    }

    override fun handleRequest(name: String?, days: Int) {
        for (handler in handlerList) {
            handler.handleRequest(name, days)
        }
    }
}

// 具體處理者
class PMHandler : Handler {
    override fun handleRequest(name: String?, days: Int) {
        if (days <= 3) {
            println("$name,pm has agreed to your leave approval")
        }
    }
}

class DirectorHandler : Handler {
    override fun handleRequest(name: String?, days: Int) {
        if (days in 4..7) {
            println("$name,director has agreed to your leave approval")
        }
    }
}

class MinisterHandler : Handler {
    override fun handleRequest(name: String?, days: Int) {
        if (days in 8..15) {
            println("$name,minister has agreed to your leave approval")
        }
    }
}

fun main() {
    val handlerChain = HandlerChain()
    handlerChain.addHandler(PMHandler()).addHandler(DirectorHandler()).addHandler(MinisterHandler())
    handlerChain.handleRequest("jack",5)
}
  1. 適配器模式:把一個類的接口轉(zhuǎn)換為客戶端所期待的另一種接口,從而使原本因接口不匹配而無法再一起工作的兩個類能夠在一起工作。
    場景:ListView與Adapter的應(yīng)用就是典型的適配器模式。
    適配器模式主要分為兩種:類適配器 和 對象適配器。
open interface USB {
    fun isUSB()
}

open interface TypeC {
    fun isTypeC()
}

open class TypeCImpl : TypeC {
    override fun isTypeC() {
        println("typeC 充電口");
    }
}

// 類適配器
class Adapter : TypeCImpl(), USB {
    override fun isUSB() {
        super.isTypeC()
    }
}

// 對象適配器
class AdapterObj(private val typeC: TypeC) : USB {
    override fun isUSB() {
        typeC.isTypeC()
    }
}
  1. 代理模式:為其他對象提供一種代理以控制這個對象的訪問。
open interface ISinger {
    fun sing()
}

class Singer : ISinger {
    override fun sing() {
        println(" singing ")
    }
}

// 靜態(tài)代理
class SingerProxy(private val singer: Singer) : ISinger {
    private val mSinger: Singer by lazy {
        singer
    }

    override fun sing() {
        println(" -- static proxy start -- ")
        mSinger.sing()
    }
}

// 動態(tài)代理,通過反射在運行時候生成代理對象的
class DynamicProxy {

    private val mSinger: Singer by lazy {
        Singer()
    }

    fun getProxy(): Any? {
        return Proxy.newProxyInstance(
            Singer::class.java.classLoader,
            mSinger.javaClass.interfaces
        ) { proxy, method, args ->
            println(" -- dynamic proxy start -- ")
            method!!.invoke(mSinger, *(args ?: arrayOfNulls<Any>(0)))
        }
    }
}

fun main() {
    SingerProxy(Singer()).sing()

    val iSinger = DynamicProxy().getProxy() as ISinger
    iSinger.sing()

}
  1. 策略模式:策略模式定義了一些列的算法,并將每一個算法封裝起來,而且使它們還可以相互替換。策略模式讓算法獨立于使用它的客戶而獨立變換。
open interface IStrategy {
    fun doAction()
}

class TweenAnimation:IStrategy{
    override fun doAction() {
        println(" -- 補間動畫 -- ")
    }
}

class FrameAnimation:IStrategy{
    override fun doAction() {
        println(" -- 逐幀動畫 -- ")
    }
}

class ValueAnimator:IStrategy{
    override fun doAction() {
        println(" -- 屬性動畫 -- ")
    }
}
class AnimatorContext {

    private var strategy: IStrategy? = null

    fun setStrategy(strategy: IStrategy?) {
        this.strategy = strategy
    }

    fun doAction() {
        strategy?.doAction()
    }
}

fun main() {
    val context =  AnimatorContext()
    val tweenAnimation = TweenAnimation() as IStrategy
    val frameAnimation = FrameAnimation() as IStrategy
    val valueAnimator = ValueAnimator() as IStrategy

    context.setStrategy(tweenAnimation)
    context.doAction()

    context.setStrategy(frameAnimation)
    context.doAction()

    context.setStrategy(valueAnimator)
    context.doAction()
}
  1. 裝飾模式:裝飾模式是在不必改變原類和使用繼承的情況下,動態(tài)地擴(kuò)展一個對象的功能。它是通過創(chuàng)建一個包裝對象,也就是裝飾來包裹真實的對象。
    裝飾模式與代理模式區(qū)別:代理模式是為了實現(xiàn)對象的控制,可能被代理的對象難以直接獲得或者是不想暴露給客戶端,而裝飾者模式是繼承的一種替代方案,在避免創(chuàng)建過多子類的情況下為被裝飾者提供更多的功能。
open interface Component {
    fun operate()
}

class ConcreteComponent : Component {
    override fun operate() {
        println(" -- ConcreteComponent operate -- ")
    }
}

abstract class Decoration : Component {
    private var component: Component ? = null

    fun setComponent(component: Component?) {
        this.component = component
    }

    override fun operate() {
        component?.operate()
    }
}

class ConcreteComponentA : Decoration(){
    override fun operate() {
        println(" -- ConcreteComponentA operate -- ")
        super.operate()
    }
}

class ConcreteComponentB: Decoration(){
    override fun operate() {
        println(" -- ConcreteComponentB operate -- ")
        super.operate()
    }
}

fun main() {
    val component = ConcreteComponent()
    val concreteComponentA = ConcreteComponentA()
    concreteComponentA.setComponent(component);
    concreteComponentA.operate()

    val concreteComponentB =  ConcreteComponentB()
    concreteComponentB.setComponent(component);
    concreteComponentB.operate()

}
  1. 工程模式:工廠模式將目的將創(chuàng)建對象的具體過程屏蔽隔離起來,從而達(dá)到更高的靈活性。
    工廠模式可以分為三類:簡單工廠模式、工廠方法模式、抽象工廠模式。
abstract class ThreadPool {
    fun execute() {
        println(" -- 線程池 --  ")
    }
}

class FixThreadPool : ThreadPool() {
    fun fixThreadExecute() {
        println(" -- 可重用固定線程池 --  ")
    }
}

class SingleThreadPool : ThreadPool() {
    fun singleThreadExecute() {
        println(" -- 單線程化線程池 --  ")
    }
}

// 簡單工廠模式
class Factory {
    fun createThreadPool(type: String?): ThreadPool? {
        when (type) {
            "fix" -> return FixThreadPool()
            "single" -> return SingleThreadPool()
        }
        return null
    }
}

// 工廠方法模式
open interface IFactoryPool {
    fun createThreadPool(): ThreadPool
}

class FixPoolFactory : IFactoryPool {
    override fun createThreadPool(): ThreadPool {
        return FixThreadPool()
    }
}

class SinglePoolFactory : IFactoryPool {
    override fun createThreadPool(): ThreadPool {
        return SingleThreadPool()
    }
}

// 抽象工廠模式
open interface IThreadPool {
    fun createThreadPool()
}

class CachedThreadPool : IThreadPool {
    override fun createThreadPool() {
        println(" -- 可緩存線程池 create --  ")
    }
}

class ScheduledThreadPool : IThreadPool {
    override fun createThreadPool() {
        println(" -- 周期性線程池 create --  ")
    }
}

open interface IExecutor {
    fun execute()
}

class CachedThreadExecute : IExecutor {
    override fun execute() {
        println(" -- 可緩存線程池 execute --  ")
    }
}

class ScheduledThreadExecute : IExecutor {
    override fun execute() {
        println(" -- 周期性線程池 execute --  ")
    }
}

abstract class AbstractFactory {
    abstract fun createThreadPool(type: String?): IThreadPool?
    abstract fun createExecute(type: String?): IExecutor?
}

class ThreadPoolFactory : AbstractFactory() {
    override fun createThreadPool(type: String?): IThreadPool? {
        when (type) {
            "cached" -> return CachedThreadPool()
            "scheduled" -> return ScheduledThreadPool()
        }
        return null
    }

    override fun createExecute(type: String?): IExecutor? {
        return null
    }
}

class ExecutorFactory : AbstractFactory() {
    override fun createThreadPool(type: String?): IThreadPool? {

        return null
    }

    override fun createExecute(type: String?): IExecutor? {
        when (type) {
            "cached" -> return CachedThreadExecute()
            "scheduled" -> return ScheduledThreadExecute()
        }
        return null
    }
}

object FactoryProducer {
    fun getFactory(type: String): AbstractFactory? {
        when (type) {
            "cached" -> return ThreadPoolFactory()
            "scheduled" -> return ExecutorFactory()
        }
        return null
    }
}

fun main() {

    val factory = Factory()
    val fixThreadPool = factory.createThreadPool("fix")
    fixThreadPool?.let {
        val pool = it as FixThreadPool
        pool.fixThreadExecute()
    }

    val singleThreadPool = factory.createThreadPool("single")
    singleThreadPool?.let {
        val pool = it as SingleThreadPool
        pool.singleThreadExecute()
    }

    val fixPoolFactory = FixPoolFactory().createThreadPool() as FixThreadPool
    fixPoolFactory.fixThreadExecute()
    val singlePoolFactory = SinglePoolFactory().createThreadPool() as SingleThreadPool
    singlePoolFactory.singleThreadExecute()

    val threadPoolFactory = FactoryProducer.getFactory("cached")
    threadPoolFactory?.let {
        val pool =  it.createThreadPool("cached") as CachedThreadPool
        pool.createThreadPool()
    }
    val executorFactory = FactoryProducer.getFactory("scheduled")
    executorFactory?.let {
        val pool =  it.createExecute("scheduled") as ScheduledThreadExecute
        pool.execute()
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容