With (agent mode) on (adapter mode) when (decoration mode) secondary group (combination mode) can make (appearance mode) foreign (bridge mode) cell (enjoy element mode) (game)

The proxy pattern

Provides a proxy for other objects to control access to that object, including static proxy and dynamic proxy.

  • Static agent
/** implements 1 **/
interface IGamePlayer {
    fun rank(a)
    fun upgrade(a)
}

// Client
class RealGamePlayer : IGamePlayer {
    override fun rank(a) {
        println("Rank \n")}override fun upgrade(a) {
        println("Upgrade \ n")}}/ / consignor
class DelegateGamePlayer1(player:IGamePlayer) : IGamePlayer by player

/** implements 2 **/
class DelegateGamePlayer2(): IGamePlayer {
    private val delegateGaemPlayer = RealGamePlayer()

    override fun rank(a) {
        delegateGaemPlayer.rank()
    }

    override fun upgrade(a) {
        delegateGaemPlayer.upgrade()
    }
}


fun main(a){
    println("Proxy Mode 1")
    val realGamePlayer = RealGamePlayer()
    val delegateGamePlayer1 = DelegateGamePlayer1(realGamePlayer)
    delegateGamePlayer1.rank()
    delegateGamePlayer1.upgrade()

    println("Proxy Mode 2")
    val delegateGamePlayer2 = DelegateGamePlayer2()
    delegateGamePlayer2.rank()
    delegateGamePlayer2.upgrade()
}
Copy the code
  • A dynamic proxy
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy

interface IGamePlayer {
    fun rank(a)
    fun upgrade(a)
}

// Client
class RealGamePlayer : IGamePlayer {
    override fun rank(a) {
        println("Rank \n")}override fun upgrade(a) {
        println("Upgrade \ n")}}class GamePlayerHandler(private val target: Any?) : InvocationHandler {
    override fun invoke(proxy: Any? , method:Method? , args:Array<out Any>?: Any? {
        println("method ${method? .name}")
        returnmethod? .invoke(target, *(args ? : arrayOfNulls<Any>(0)))}}fun main(a) {
    val obj = RealGamePlayer()
    val player = Proxy.newProxyInstance(obj::class.java.classLoader,
            obj::class.java.interfaces, GamePlayerHandler(obj)) as IGamePlayer
    player.rank()
    player.upgrade()
}
Copy the code

Adapter mode

The Adapter pattern enables classes to work together that would otherwise not work together due to interface incompatibilities.

/** * Adapter mode ** Three features of adapter mode: 2. The adapter object combines an object that implements the new interface (this object may also not implement an interface, but simply be an object). Gb (domestic standard) socket for 3 holes, German standard (German standard) socket for 2 holes * problem: a domestic tourist to Travel in Germany, with gb charger (3 holes) how to use the German standard jack (2 holes) * solution: power conversion adapter */


interface GBSocketInterface{
    // Three-hole plug for charging
    fun powerWithThreeFlat(a)
}

class GBSocket:GBSocketInterface{
    override fun powerWithThreeFlat(a) {
        println("Gb: Charge with three-hole plug")}}interface DBSocketInterface{
    // Two hole plug for charging
    fun powerWithTwoFlat(a)
}

class DBSocket:DBSocketInterface{
    override fun powerWithTwoFlat(a) {
        println("German standard: Charge with two-hole plug")}}// Hotel in Germany
class DHotel(private val dbSocket:DBSocketInterface){
    / / charge
    fun charge(a){ dbSocket? .powerWithTwoFlat() } }/ / adapter
class SocketAdapter(private val gbSocket: GBSocketInterface):DBSocketInterface{
    override fun powerWithTwoFlat(a) {
        gbSocket.powerWithThreeFlat()
    }
}

val gbSocket = GBSocket()
val adapter = SocketAdapter(gbSocket)
val hotel = DHotel(adapter)
hotel.charge()
Copy the code

Decorator mode

Dynamically extend the functionality of a class

class Text(val text: String) {
    fun draw(a) = print("$text")}/** Dynamically extend the functionality of classes */
fun Text.underline(decorated: Text. () - >Unit) {
    print("_")
    this.decorated()
    print("_")}fun Text.background(decorated: Text. () - >Unit) {
    print("\u001B[43m")
    this.decorated()
    print("\u001B[0m")}fun preDecorated(decorated: Text. () - >Unit): Text.() -> Unit {
    return { background { underline { decorated() } } }
}

val text = preDecorated {
    Text("hello").draw()
}
Copy the code

Portfolio model

Combining objects into a tree structure to represent the relationship between parts of the whole, Composite allows users to use individual objects and Composite objects consistently.

interface AbstractFile {
    var childCount: Int
    fun getChild(i: Int): AbstractFile
    fun size(a): Long
}

class File(val size: Long.override var childCount: Int = 0) : AbstractFile {
    override fun getChild(i: Int): AbstractFile {
        throw RuntimeException("You shouldn't call the method in File")}override fun size(a) = size
}

class Folder(override var childCount: Int) : AbstractFile {
    override fun getChild(i: Int): AbstractFile {
        return File(100)}override fun size(a): Long = (0 until childCount).map { getChild(it).size() }.sum()
}

val folder = Folder(10)
print("size = ${folder.size()}")
Copy the code

The appearance model

Provides a simplified unified interface for a complex subsystem

class ComplexSystemStore(val filePath: String) {
    init {
        println("reading data from filr $filePath\n")}val store = HashMap<String, String>()

    fun store(key: String, payload: String) {
        store.put(key, payload)
    }

    fun read(key: String)= store[key] ? :""

    fun commit(a) = println("storing cached data: $store to file $filePath\n")}data class User(val login: String)

/ / appearance
class UserRepository {
    val systemPreference = ComplexSystemStore("/data/default.prefs")

    fun save(user: User) {
        systemPreference.store("USER_KEY", user.login)
        systemPreference.commit()
    }

    fun findFirst(a) = User(systemPreference.read("USER_KEY"))}val repository = UserRepository()
val user = User("hellokit")
repository.save(user)
val resultUser = repository.findFirst()
print(resultUser)
Copy the code

The bridge model

Separate the abstract from its implementation so that they can change independently.

abstract class Shape() {
    abstract fun draw(a)
}


class Circle(val color: Color) : Shape() {
    override fun draw(a) {
        println("I am circle color is ${color.name()}\n")}}class Square(val color: Color) : Shape() {
    override fun draw(a) {
        print("I am square color is ${color.name()}\n")}}abstract class Color() {
    abstract fun name(a): String
}

class Red() : Color() {
    override fun name(a) = "red"
}

class Blue : Color() {
    override fun name(a) = "blue"
}

class Yellow : Color() {
    override fun name(a) = "yellow"
}

val red = Red()
val blue = Blue()
val circle = Circle(red)
val square = Square(blue)
circle.draw()
square.draw()
Copy the code

The flyweight pattern

There are a large number of similar objects in the system, or scenarios that require buffer pools, or scenarios where fine-grained objects all have similar external states and their internal states are independent of the environment.

import java.util.*

interface BottleCap {
    // Cap color
    val color:String
    // Qr code information
    fun disQRContent(qeContent: QRContent): String
}

class QRContent {
    private lateinit var mQRContent: String
    private lateinit var mUUid: String

    init {
        mUUid = UUID.randomUUID().toString()
    }

    fun setmQRContent(mQRContent: String) {
        this.mQRContent = mQRContent
    }

    fun getmQRContent(a): String {
        mQRContent = "Unique ID of qr code:$mUUid\n Get the winning information according to ID${Random().nextInt(6) + 1}Award,"
        return mQRContent
    }

}

class ConcreteBottleCap(override val color: String) : BottleCap {

    override fun disQRContent(qeContent: QRContent): String {
        return "Cap color${color}\n Qr code content${qeContent.getmQRContent()}"}}class BottleWeightFactory {
    companion object {
        val map = HashMap<String, BottleCap>()

        fun getBottleCap(color: String): BottleCap {
            if (map.get(color) ! =null) {
                return map[color] as BottleCap
            } else {
                val cfw = ConcreteBottleCap(color)
                map.put(color, cfw)
                return cfw
            }
        }
    }
}

val bottleCap1 = BottleWeightFactory.getBottleCap("Blue")
val bottleCap2 = BottleWeightFactory.getBottleCap("Blue")

print("BottleCap1 award result =${bottleCap1.disQRContent(QRContent())}\n")
print("BottleCap2 award result =${bottleCap2.disQRContent(QRContent())}\n")
Copy the code