//本文參考菜鳥教程
設(shè)計模式主要分為三大類創(chuàng)建型模式盗迟,結(jié)構(gòu)型模式,行為型模式婆殿,本文主要講行為型模式
行為型模式诈乒,共十一種:策略模式罩扇、模板方法模式婆芦、觀察者模式怕磨、迭代子模式、責(zé)任鏈模式消约、命令模式肠鲫、備忘錄模式、狀態(tài)模式或粮、訪問者模式导饲、中介者模式、解釋器模式氯材。
1.策略模式
定義:一個類的行為或其算法可以在運行時更改渣锦。這種類型的設(shè)計模式屬于行為型模式。
interface Strategy{
fun operation(num:Int,num2:Int):Int
}
class AddStrategyImpl:Strategy{
override fun operation(num: Int, num2: Int) = num + num2
}
class RemoveStrategyImpl:Strategy{
override fun operation(num: Int, num2: Int) = num - num2
}
class StrategyImpl(private var strategy: Strategy){
fun doStrategy(num: Int,num2: Int){
strategy.operation(num,num2)
}
}
2.模版模式
定義:一個抽象類公開定義了執(zhí)行它的方法的方式/模板氢哮。它的子類可以按需要重寫方法實現(xiàn)
abstract class Temple {
abstract fun one()
abstract fun two()
abstract fun three()
fun dayDo() {
one()
two()
three()
}
}
class TempleTest : Temple() {
override fun one() {
println("1")
}
override fun two() {
println("2")
}
override fun three() {
println("3")
}
}
3.觀察者模式
定義:定義對象間的一種一對多的依賴關(guān)系袋毙,當(dāng)一個對象的狀態(tài)發(fā)生改變時,所有依賴于它的對象都得到通知并被自動更新冗尤。
interface Subject{
fun registerObserver(o:Observer)
fun removeObserver(o:Observer)
fun notifyObserver()
}
interface Observer{
fun update(message:String)
}
class WechatServer:Subject{
var list = mutableListOf<Observer>()
var message:String = ""
override fun registerObserver(o: Observer) {
list.add(o)
}
override fun removeObserver(o: Observer) {
if(list.isNotEmpty()){
list.remove(o)
}
}
override fun notifyObserver() {
list.forEach {
it.update(message)
}
}
fun setInfo(){
println("觀測者")
message = "粗發(fā)事件"
notifyObserver()
}
}
class ObserverUser(val name:String):Observer{
private var message: String = ""
override fun update(message: String) {
this.message = message
readMessage()
}
fun readMessage(){
println("獲取到消息")
}
}
fun main() {
val server = WechatServer()
val userLi = ObserverUser("li")
server.registerObserver(userLi)
server.setInfo()
}
4.迭代器模式
定義:提供一種方法順序訪問一個聚合對象中各個元素, 而又無須暴露該對象的內(nèi)部表示
參考java的iterator
5.責(zé)任鏈模式
定義:如果有多個對象有機會處理請求听盖,責(zé)任鏈可使請求的發(fā)送者和接受者解耦,請求沿著責(zé)任鏈傳遞裂七,直到有一個對象處理了它為止皆看。
abstract class AbstractLogger {
companion object {
val INFO = 1
val DEBUG = 2
val ERROR = 3
}
private var level: Int = 0
var nextLogger: AbstractLogger? = null
fun logMessage(level: Int, message: String) {
if (this.level <= level) {
write(message)
}
nextLogger?.logMessage(level, message)
}
protected abstract fun write(message: String)
}
class ConsoleLogger(level: Int) : AbstractLogger() {
override fun write(message: String) {
println("stand console::logger$message")
}
}
class ErrorLogger(level: Int) : AbstractLogger() {
override fun write(message: String) {
println("error console::logger$message")
}
}
class FileLogger(level: Int) : AbstractLogger() {
override fun write(message: String) {
println("File console::logger$message")
}
}
object ChainTest {
fun getChainOfLoggers(): AbstractLogger {
val errorLogger: AbstractLogger = ErrorLogger(AbstractLogger.ERROR)
val fileLogger: AbstractLogger = FileLogger(AbstractLogger.DEBUG)
val consoleLogger: AbstractLogger = ConsoleLogger(AbstractLogger.INFO)
errorLogger.nextLogger = fileLogger
fileLogger.nextLogger = consoleLogger
return errorLogger
}
}
fun main() {
val loggerChain: AbstractLogger = getChainOfLoggers()
loggerChain.logMessage(AbstractLogger.INFO, "This is an information.")
loggerChain.logMessage(
AbstractLogger.DEBUG,
"This is a debug level information."
)
loggerChain.logMessage(
AbstractLogger.ERROR,
"This is an error information."
)
}
6.命令模式
定義:將一個請求封裝為一個對象,使發(fā)出請求的責(zé)任和執(zhí)行請求的責(zé)任分割開背零。這樣兩者之間通過命令對象進行溝通腰吟,這樣方便將命令對象進行儲存、傳遞、調(diào)用派殷、增加與管理莫其。
interface Order{
fun execute()
}
class Stock{
val name = "ABC"
val quantity = 10
fun buy(){
println("bubbly")
}
fun sell(){
println("sell")
}
}
class SellStock(private val stock: Stock):Order{
override fun execute() {
stock.sell()
}
}
class BuyStock(private val stock: Stock):Order{
override fun execute() {
stock.buy()
}
}
class Broker {
private val orderList: MutableList<Order> = ArrayList()
fun takeOrder(order: Order) {
orderList.add(order)
}
fun placeOrders() {
for (order in orderList) {
order.execute()
}
orderList.clear()
}
}
fun main() {
val abcStock = Stock()
val buyStockOrder = BuyStock(abcStock)
val sellStockOrder = SellStock(abcStock)
val broker = Broker()
broker.takeOrder(buyStockOrder)
broker.takeOrder(sellStockOrder)
broker.placeOrders()
}
7.狀態(tài)模式
定義:在狀態(tài)模式中,我們創(chuàng)建表示各種狀態(tài)的對象和一個行為隨著狀態(tài)對象改變而改變的 context 對象禾乘。
data class StateContext(var state: State? = null)
interface State{
fun doAction(context: StateContext)
}
class StartState:State{
override fun doAction(context: StateContext) {
println("is start state")
context.state = this
}
override fun toString(): String {
return "Start state"
}
}
class StopState:State{
override fun doAction(context: StateContext) {
println("is stop state")
context.state = this
}
override fun toString(): String {
return "stop state"
}
}
fun main() {
val context = StateContext()
val startState = StartState()
startState.doAction(context)
println(context.state.toString())
val stopState = StopState()
stopState.doAction(context)
println(context.state.toString())
}
8.備忘錄模式
定義: 在不破壞封裝性的前提下,捕獲一個對象的內(nèi)部狀態(tài)虽缕,并在該對象之外保存這個狀態(tài)始藕,以便以后當(dāng)需要時能將該對象恢復(fù)到原先保存的狀態(tài)。該模式又叫快照模式
data class MementoTest(var state:String)
class Originator{
var state:String = ""
fun saveStateToMemento():MementoTest = MementoTest(state)
fun getStateFromMemento(mementoTest: MementoTest){
state = mementoTest.state
}
}
class CareTaker {
private val mementoList: MutableList<MementoTest> = ArrayList<MementoTest>()
fun add(state: MementoTest) {
mementoList.add(state)
}
operator fun get(index: Int): MementoTest {
return mementoList[index]
}
}
fun main() {
val originator = Originator()
val careTaker = CareTaker()
originator.state = "State #1"
originator.state = "State #2"
careTaker.add(originator.saveStateToMemento())
originator.state = "State #3"
careTaker.add(originator.saveStateToMemento())
originator.state = "State #4"
println("Current State: " + originator.state)
originator.getStateFromMemento(careTaker[0])
println("First saved State: " + originator.state)
originator.getStateFromMemento(careTaker[1])
println("Second saved State: " + originator.state)
}
9.訪問者模式
定義:我們使用了一個訪問者類氮趋,它改變了元素類的執(zhí)行算法伍派。通過這種方式,元素的執(zhí)行算法可以隨著訪問者改變而改變剩胁。這種類型的設(shè)計模式屬于行為型模式诉植。根據(jù)模式,元素對象已接受訪問者對象昵观,這樣訪問者對象就可以處理元素對象上的操作晾腔。
class VisitorTest {
interface ComputerPart{
fun accept(computerPartVisitor: ComputerPartVisitor)
}
interface ComputerPartVisitor {
fun visit(computer: Computer?)
fun visit(mouse: Mouse?)
fun visit(keyboard: Keyboard?)
fun visit(monitor: Monitor?)
}
class Keyboard:ComputerPart{
override fun accept(computerPartVisitor: ComputerPartVisitor) {
computerPartVisitor.visit(this)
}
}
class Mouse:ComputerPart{
override fun accept(computerPartVisitor: ComputerPartVisitor) {
computerPartVisitor.visit(this)
}
}
class Monitor:ComputerPart{
override fun accept(computerPartVisitor: ComputerPartVisitor) {
computerPartVisitor.visit(this)
}
}
class Computer : ComputerPart {
private var parts: Array<ComputerPart> = arrayOf(Mouse(), Keyboard(), Monitor())
override fun accept(computerPartVisitor: ComputerPartVisitor) {
for (i in parts.indices) {
parts[i].accept(computerPartVisitor)
}
computerPartVisitor.visit(this)
}
}
class ComputerPartDisplayVisitor : ComputerPartVisitor {
override fun visit(computer: Computer?) {
println("Displaying Computer.")
}
override fun visit(mouse: Mouse?) {
println("Displaying Mouse.")
}
override fun visit(keyboard: Keyboard?) {
println("Displaying Keyboard.")
}
override fun visit(monitor: Monitor?) {
println("Displaying Monitor.")
}
}
}
fun main() {
val computer: ComputerPart = VisitorTest.Computer()
computer.accept(ComputerPartDisplayVisitor())
}
10.中介者模式
定義:是用來降低多個對象和類之間的通信復(fù)雜性舌稀。這種模式提供了一個中介類,該類通常處理不同類之間的通信灼擂,并支持松耦合壁查,使代碼易于維護。
class MediatorTest {
object ChatRoom {
fun showMessage(user: User, message: String) {
println(
Date().toString()
.toString() + " [" + user.name + "] : " + message
)
}
}
class User(var name: String) {
fun sendMessage(message: String) {
ChatRoom.showMessage(this, message)
}
}
}
fun main() {
val robert = User("Robert")
val john = User("John")
robert.sendMessage("Hi! John!")
john.sendMessage("Hello! Robert!")
}