设计模式

目的分类:
创建型Creational 与对象的创建有关;
结构型Structural 处理类或对象的组合;
行为型Behavioral 对类或对象怎么样交互和怎么样分配职责进行描述
范围分类:
类模式处理类和子类之间的关系,是静态的,在编译时刻便确定下来了。
对象模式处理对象之间的关系,运行时时刻变化,具有动态性。

创建型类模式将对象的部分创建工作延迟到子类,而创建型对象模式则将它延迟到另一个对象中。结构型类模式使用继承机制来组合类,而结构型对象模式则描述了对象的组装方式。行为型类模式使用继承描述算法和控制流,而行为型对象模式则描述一组对象怎样协作完成单个对象所无法完成的任务。

23个设计模式:

Factory Method:定义一个用于创建对象的接口,让子类决定将哪一个类实例化。使一个类的实例化延迟到其子类。

class ShapeFactory {
fun getShape(shapeType: String): Shape? {
if (shapeType == null) return null

if (shapeType == "circle") {
return Circle()
        } else if (shapeType == "rectangle") {
return Rectangle()
        } else if (shapeType == "square") {
return Square()
}
        return null;
}
}

Abstract Factory 提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。根据抽象程度分为:简单工厂模式(静态工厂),工厂方法模式,抽象工厂模式。

abstract class AbstractFactory {
abstract fun getColor(color: String): Color?
abstract fun getShape(shape: String): Shape?
}

class ShapeFactory : AbstractFactory() {
override fun getColor(color: String): Color? {
return null
}

override fun getShape(shape: String): Shape? {
if (shape == null) return null

if (shape == "circle") {
return Circle()
} else if (shape == "rectangle") {
return Rectangle()
} else if (shape == "square") {
return Square()
}
return null;
}
}

class ColorFactory : AbstractFactory() {
override fun getColor(color: String): Color? {
if (color == null) return null

if (color == "red") {
return Red()
} else if (color == "green") {
return Green()
} else if (color == "blue") {
return Blue()
}
return null
}

override fun getShape(shape: String): Shape? {
return null;
}
}

class FactoryProducer {
companion object {
fun getFactory(choice: String): AbstractFactory? {
if (choice == "shape") {
return ShapeFactory()
} else if (choice == "color") {
return ColorFactory()
}
return null
}
}
}

Adapter 将一个类的接口转换成客户希望的另外一个接口。

fun main(args: Array<String>) {
val audioPlayer = AudioPlayer()
audioPlayer.play("mp3","xxx")
audioPlayer.play("mp4","yyy")
audioPlayer.play("vlc","zzz")
}

interface MediaPlayer {
fun play(audioType: String, fileName: String)
}

class AudioPlayer : MediaPlayer {

var mediaAdapter: MediaAdapter? = null
override fun play(audioType: String, fileName: String) {
if ("mp3" == audioType) {
println("playing mp3 file name:$fileName")

} else if ("vlc" == audioType || "mp4" == audioType) {
mediaAdapter = MediaAdapter(audioType)
mediaAdapter?.play(audioType, fileName)
} else {
println("invalid media")
}
}
}

interface AdvanceMediaPlayer {
fun playVlc(fileName: String)
fun playMp4(fileName: String)
}

class VlcPlayer : AdvanceMediaPlayer {
override fun playVlc(fileName: String) {
// do nothing
println("playing vlc file name:$fileName")
}

override fun playMp4(fileName: String) {
//do nothing
}
}

class Mp4Player : AdvanceMediaPlayer {
override fun playVlc(fileName: String) {
// do nothing
}

override fun playMp4(fileName: String) {
println("playing mp4 file Name:$fileName")
}
}

class MediaAdapter(audioType: String) : MediaPlayer {

val advancedMusicPlayer: AdvanceMediaPlayer?

init {
if (audioType == "vlc") {
advancedMusicPlayer = VlcPlayer()
} else if (audioType == "mp4") {
advancedMusicPlayer = Mp4Player()
} else {
advancedMusicPlayer = null
}
}


override fun play(audioType: String, fileName: String) {
if (audioType == "vlc") {
advancedMusicPlayer?.playVlc(fileName);
} else if (audioType == "mp4") {
advancedMusicPlayer?.playMp4(fileName);
}
}

}

Bridge:将抽象部分与它的实现部分分离,使它们都可以独立地变化。

fun main(args: Array<String>) {
val redCircle = Circle(100, 100, 10, RedCircle())
val greenCircle = Circle(50, 50, 10, GreenCircle())

redCircle.draw()
greenCircle.draw()
}

interface DrawAPI {
fun drawCircle(radius: Int, x: Int, y: Int)
}

class RedCircle : DrawAPI {
override fun drawCircle(radius: Int, x: Int, y: Int) {
println("Drawing Circle color red raduis : $radius ,($x,$y)")
}
}

class GreenCircle : DrawAPI {
override fun drawCircle(radius: Int, x: Int, y: Int) {
println("Drawing Circle color green raduis : $radius ,($x,$y)")
}
}

abstract class Shape constructor(val drawAPI: DrawAPI) {
abstract fun draw()
}

class Circle(val x: Int, val y: Int, val radius: Int, drawAPI: DrawAPI) : Shape(drawAPI) {
override fun draw() {
drawAPI.drawCircle(radius, x, y)
}

}

Builder 将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

fun main(args: Array<String>) {
val builder = MealBuilder()
val meal = builder.prepareVegMeal()
meal.showItems()
print(meal.getCost())
}

interface Item {
fun name(): String
fun packing(): Packing
fun price(): Float
}

interface Packing {
fun pack(): String
}

class Wrapper : Packing {
override fun pack(): String {
return "wrapper"
}
}

class Bottle : Packing {
override fun pack(): String {
return "bottle"
}
}

abstract class Burger : Item {
override fun packing(): Packing {
return Wrapper()
}

override abstract fun price(): Float
}

abstract class ColdDrink : Item {
override fun packing(): Packing {
return Bottle()
}

override abstract fun price(): Float
}

class VegBurger : Burger() {
override fun name(): String {
return "veg burger"
}

override fun price(): Float {
return 0.25f
}
}

class ChickenBurger : Burger() {
override fun name(): String {
return "chicken burger"
}

override fun price(): Float {
return 3.14f
}
}

class Coke : ColdDrink() {
override fun name(): String {
return "coke"
}

override fun price(): Float {
return 1.0f
}
}

class Pepsi : ColdDrink() {
override fun name(): String {
return "pepsi"
}

override fun price(): Float {
return 1.2f
}
}

class Meal {
val items = ArrayList<Item>()

fun addItem(item: Item) {
items.add(item)
}

fun getCost(): Float {
var cost = 0.0
for (item in items) {
cost += item.price()
}
return cost.toFloat()
}

fun showItems() {
for (item in items) {
println("Item: ${item.name()},Packing: ${item.packing()},Price: ${item.price()}")
}
}
}

class MealBuilder {
fun prepareVegMeal(): Meal {
val meal = Meal()
meal.addItem(VegBurger())
meal.addItem(Coke())
return meal
}

fun prepareNonVegMeal(): Meal {
val meal = Meal()
meal.addItem(ChickenBurger())
meal.addItem(Pepsi())
return meal
}
}

Chain of Responsibility:为解除请求的发送者和接收者之间的耦合,而使多个对象都有机会处理这个请求。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它。

fun main(args: Array<String>) {

val errorlog = ErrorLogger(AbstractLogger.ERROR)
val filelog = FileLogger(AbstractLogger.DEBUG)
val consolelog = ConsoleLogger(AbstractLogger.INFO)

errorlog.nextLogger = filelog
filelog.nextLogger = consolelog

errorlog.logMessage(AbstractLogger.INFO, "this is information")
println("---")
errorlog.logMessage(AbstractLogger.DEBUG, "this is debug")
println("---")
errorlog.logMessage(AbstractLogger.ERROR, "this is error")
println("---")
}

abstract class AbstractLogger(val level: Int) {

companion object {
val INFO: Int = 1
val DEBUG: Int = 2
val ERROR: Int = 3
}

var nextLogger: AbstractLogger? = null

fun logMessage(level: Int, message: String) {
if (this.level <= level) write(message)

if (nextLogger != null) nextLogger?.logMessage(level, message)
}

abstract fun write(message: String)

}

class ConsoleLogger(level: Int) : AbstractLogger(level) {

override fun write(message: String) {
println("console:logger " + message)
}
}

class ErrorLogger(level: Int) : AbstractLogger(level) {
override fun write(message: String) {
println("error:logger " + message)
}
}

class FileLogger(level: Int) : AbstractLogger(level) {
override fun write(message: String) {
println("file:logger " + message)
}
}

Command:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可取消的操作。

fun main(args: Array<String>) {
val stock = Stock()
val buyStockOrder = BuyStock(stock)
val sellStockOrder = SellStock(stock)

val broker = Broker()
broker.takeOrder(buyStockOrder)
broker.takeOrder(sellStockOrder)

broker.placeOrders()
}

interface Order {
fun execute()
}

class Stock {
val name: String = "ABC"
val quantity: Int = 10

fun buy() {
println("Stock [name:$name, Quantity:$quantity] bought")
}

fun sell() {
println("Stock [Name:$name, Quantity:$quantity] sold")
}
}

class BuyStock(val abcStock: Stock) : Order {
override fun execute() {
abcStock.buy()
}
}

class SellStock(val abcStock: Stock) : Order {
override fun execute() {
abcStock.sell()
}
}

class Broker {
val orderList: ArrayList<Order> = ArrayList<Order>()

fun takeOrder(order: Order) {
orderList.add(order)
}

fun placeOrders() {
println("size ${orderList.size}")
for (item in orderList) {
item.execute()
}
orderList.clear()
}
}

Composite:将对象组合成树形结构以表示 部分-整体 的层次结构。使得客户对单个对象和复合对象的使用具有一致性。

class Employee(val name: String, val dept: String, val sal: Int) {

val subordinates: List<Employee>

init {
subordinates = ArrayList<Employee>()
}

fun add(e: Employee) {
subordinates.plus(e)
}

fun remove(e: Employee) {
subordinates.minus(e)
}

override fun toString(): String {
return ("Employee:[Name:$name,dept:$dept,salary:$sal")
}

}

Decorator:动态地给一个对象添加一些额外的职责。就扩展功能而言,模式比生成子类方式更为灵活。

fun main(args: Array<String>) {
val circle: Shape = Circle()
val redCircle: Shape = RedShapeDecorator(circle)
val redRectangle: Shape = RedShapeDecorator(Rectangle())

redCircle.draw()
redRectangle.draw()
}

interface Shape {
fun draw()
}

class Rectangle : Shape {
override fun draw() {
println("rectangle")
}
}

class Circle : Shape {
override fun draw() {
println("circle")
}
}

abstract class ShapeDecorator(val decoratedShape: Shape) : Shape {
override fun draw() {
decoratedShape.draw()
}
}

class RedShapeDecorator(decoratedShape: Shape) : ShapeDecorator(decoratedShape) {
override fun draw() {
decoratedShape.draw()
setRedBorder(decoratedShape)
}

fun setRedBorder(decoratedShape: Shape) {
println("red")
}
}

Facade:为子系统中的一组接口提供一个一致的界面,定义了一个高层接口,这个接口使得这一子系统更加容易使用。involves a single class which provides simplified methods required by client and delegates calls to methods of existing system classes.

fun main(args: Array<String>) {

val shapeMaker = ShapeMaker()
shapeMaker.drawCircle()
shapeMaker.drawRectangle()
}

interface Shape {
fun draw()
}

class Rectangle : Shape {
override fun draw() {
println("rectangle draw");
}
}

class Square : Shape {
override fun draw() {
println("square draw")
}
}

class Circle : Shape {
override fun draw() {
println("circle draw")
}
}

class ShapeMaker {

val circle: Shape
val rectangle: Shape
val square: Shape

init {
circle = Circle()
rectangle = Rectangle()
square = Square()
}

fun drawCircle() {
circle.draw()
}

fun drawRectangle() {
rectangle.draw()
}

fun drawSquare() {
square.draw()
}
}

Flyweight:运用共享技术有效地支持大量细粒度的对象。

fun main(args: Array<String>) {

for (i in 1..20) {
val circle = ShapeFactory.getCircle()
circle.draw()
}
}

interface Shape {
fun draw()
}

class Circle(val color: String) : Shape {

var x: Int = 0
var y: Int = 0
var radius: Int = 0

override fun draw() {
println("Circle: Draw()[color:$color,x:$x,y:$y,radius:$radius")
}
}

object ShapeFactory {
val circleMap: HashMap<String, Shape> = HashMap()

fun getCircle(): Shape {
val color = getRandomColor()
var circle = circleMap.get(color)

if (circle == null) {
circle = Circle(color)
circleMap.put(color, circle)
}
return circle
}

val colors = arrayOf("red", "green", "blue", "white")

fun getRandomColor(): String {
return colors[(Math.random() * colors.size).toInt()]
}
}

Interpreter:给定一个语言,定义它的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中的句子。

fun main(args: Array<String>) {
val isMale: Expression = getMaleExpression()
val isMarriedWoman = getMarriedWomanExpression()

println("John is male?" + isMale.interpret("John"))
println("Julie is a married women?" + isMarriedWoman.interpret("Married Julie"))
}

fun getMaleExpression(): Expression {
val robert: Expression = TerminaExpression("Robert")
val john: Expression = TerminaExpression("John")
return OrExpression(robert, john)
}

fun getMarriedWomanExpression(): Expression {
val robert: Expression = TerminaExpression("Julie")
val john: Expression = TerminaExpression("Married")
return AndExpression(robert, john)
}

interface Expression {
fun interpret(context: String): Boolean
}

class TerminaExpression(val data: String) : Expression {
override fun interpret(context: String): Boolean {
if (context.contains(data)) {
return true
}
return false
}
}

class OrExpression(val expr1: Expression, val expr2: Expression) : Expression {
override fun interpret(context: String): Boolean {
return expr1.interpret(context) || expr2.interpret(context)
}
}

class AndExpression(val expr1: Expression, val expr2: Expression) : Expression {
override fun interpret(context: String): Boolean {
return expr1.interpret(context) && expr2.interpret(context)
}
}

Iterator:提供一种方法顺序访问一个聚合对象中各个元素,而又不需暴露该对象的内部表示。

fun main(args: Array<String>) {
val nameRepository = NameRepository()
val iter = nameRepository.getIterator()
while (iter.hasNext()) {
println("Name: " + iter.next())
}
}

interface Iterator {
fun hasNext(): Boolean
fun next(): Object?
}

interface Container {
fun getIterator(): Iterator
}

class NameRepository : Container {

val names = arrayOf("watson", "mathilda", "love", "west")

override fun getIterator(): Iterator {
return NameIterator()
}

inner class NameIterator : Iterator {

var index = 0
override fun next(): Object? {
if (this.hasNext()) {
return names.get(index++) as Object
}
return null
}

override fun hasNext(): Boolean {
return if (index < names.size) true else false
}
}
}

Mediator:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变她们之间的交互。

fun main(args: Array<String>) {

val watson = User("watson")
val mathida = User("mathida")

watson.sendMessage("hi ma")
mathida.sendMessage("hi wa")
}

class ChatRoom {
companion object {
fun showMessage(user: User, msg: String) {
println(Date().toString() + " [${user.name}] : $msg")
}
}
}

class User(val name: String) {

fun sendMessage(message: String) {
ChatRoom.showMessage(this, message)
}
}

Memento:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到保存状态。

fun main(args: Array<String>) {
val originator = Originator()
val careTaker = CareTaker()

originator.state = "s 1"
originator.state = "s 2"
careTaker.add(originator.saveStateToMemento())

originator.state = "s 3"
careTaker.add(originator.saveStateToMemento())

originator.state = "s 4"
println("current state -> " + originator.state)

originator.getStateFromMemeto(careTaker.get(0))
println("first save state ->" + originator.state)

originator.getStateFromMemeto(careTaker.get(1))
println("secode save state ->" + originator.state)

}

class Memento(val state: String) {

}

class Originator() {

var state: String = ""

fun saveStateToMemento(): Memento {
return Memento(state)
}

fun getStateFromMemeto(memento: Memento) {
state = memento.state
}
}

class CareTaker {
val mementoList: ArrayList<Memento> = ArrayList<Memento>()

fun add(state: Memento) {
mementoList.add(state)
}

fun get(index: Int): Memento {
return mementoList.get(index)
}
}

Obserrver:定义对象间的一种一对多的依赖关系,以便当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动刷新。

fun main(args: Array<String>) {
val subject = Subject()
HexaObserver(subject)
OctalObserver(subject)
BinaryObserver(subject)

subject.state = 15
subject.state = 10
}

class Subject {
val observers = ArrayList<Observer>()
var state: Int = 0
set(value) {
field = value
notifyAllObservers()
}

fun attach(observer: Observer) {
observers.add(observer)
}

fun notifyAllObservers() {
println("notify")
for (item in observers) {
item.update()
}
}
}

abstract class Observer {
var subject: Subject? = null
abstract fun update()
}

class BinaryObserver(subject: Subject) : Observer() {
init {
this.subject = subject
subject.attach(this)
}

override fun update() {
println("Binary String: " + Integer.toBinaryString(subject?.state ?: 0))
}
}

class OctalObserver(subject: Subject) : Observer() {
init {
this.subject = subject
subject.attach(this)
}

override fun update() {
println("Octal String: " + Integer.toOctalString(subject?.state ?: 0))
}
}

class HexaObserver(subject: Subject) : Observer() {
init {
this.subject = subject
subject.attach(this)
}

override fun update() {
println("Hexa String: " + Integer.toHexString(subject?.state ?: 0))
}
}

Prototype:用原型实例指定创建对象的种类,并且通过拷贝这个原型来创建新的对象。

fun main(args: Array<String>) {
ShapeCache.loadCache()

val cloneShape = ShapeCache.getShape("1") as Shape
print(cloneShape.type)
}

abstract class Shape : Cloneable {

var id: String = ""
var type: String = ""

abstract fun draw()

public override fun clone(): Any {
var clone: Any? = null
try {
clone = super.clone()
} catch (e: Exception) {
e.printStackTrace()
}

return clone ?: super.clone()
}
}

class Rectangle() : Shape() {

init {
type = "Rectangle"
}

override fun draw() {
print("Rectangle")
}
}

class Square() : Shape() {

init {
type = "Square"
}

override fun draw() {
print("Square")
}
}

class Circle() : Shape() {

init {
type = "Circle"
}

override fun draw() {
print("Circle")
}
}

object ShapeCache {

val shapeMap: HashMap<String, Shape> = HashMap()

fun getShape(shapId: String): Shape {
val cachedShape: Shape? = shapeMap.get(shapId)
return (cachedShape?.clone()) as Shape
}

fun loadCache(){
val circle = Circle()
circle.id = "1"
shapeMap.put(circle.id,circle)
}
}

Proxy:为其他对象提供一个代理以控制对这个对象的访问。

fun main(args: Array<String>) {
val image: Image = ProxyImage("/file/love")

image.display()
image.display()
}

interface Image {
fun display()
}

class RealImage(val fileName: String) : Image {

init {
loadFromDisk(fileName)
}

override fun display() {
println("displaying " + fileName)
}

fun loadFromDisk(fileName: String) {
println("loading")
}

}

class ProxyImage(val fileName: String) : Image {

var realImage: RealImage? = null

override fun display() {
if (realImage == null) {
realImage = RealImage(fileName)
}
realImage?.display()
}

}

Singleton:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

object SingleObject{
var name = "watson"
}

State:允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它所属的类。

fun main(args: Array<String>) {
val context = Context()

val startState:State = StartState()
startState.doAction(context)

println(context.state.toString())

val stopState:State = StopState()
stopState.doAction(context)

println(context.state.toString())
}

interface State {
fun doAction(context: Context)
}

class StartState : State {

override fun doAction(context: Context) {
println("player is in start state")
context.state = this
}

override fun toString(): String {
return "Start state"
}

}

class StopState : State{

override fun doAction(context: Context) {
println("Player is in stop state")
context.state = this
}

override fun toString(): String {
return "Stop State"
}

}

class Context {
var state: State? = null;

init {
state = null
}
}

Strategy:定义一系列的算法,把它们一个个封装起来,并且可以使它们可以相互替换。使得算法的变化可独立于使用它的客户。

fun main(args: Array<String>) {
var context = Context(OperationAdd())
println("add ->" + context.executeStrategy(10, 5))

context = Context(OperationSubstract())
println("sub ->" + context.executeStrategy(10, 5))

context = Context(OperationMultiply())
println("multi ->" + context.executeStrategy(10, 5))

}

interface Strategy {
fun doOperation(num1: Int, num2: Int): Int
}

class OperationAdd : Strategy {
override fun doOperation(num1: Int, num2: Int): Int {
return num1 + num2
}
}

class OperationSubstract : Strategy {
override fun doOperation(num1: Int, num2: Int): Int {
return num1 - num2
}
}

class OperationMultiply : Strategy {
override fun doOperation(num1: Int, num2: Int): Int {
return num1 * num2
}
}

class Context(val strategy: Strategy) {

fun executeStrategy(num1: Int, num2: Int): Int {
return strategy.doOperation(num1, num2)
}

}

Template Method:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

import com.sun.org.glassfish.gmbal.GmbalException

fun main(args: Array<String>) {

var game: Game = Cricket()
game.play()

game = Football()
game.play()

}

abstract class Game {
abstract fun initialize()
abstract fun startPlay()
abstract fun endPlay()

final fun play() {
initialize()
startPlay()
endPlay()
}
}

class Cricket : Game() {
override fun initialize() {
println("c game init")
}

override fun startPlay() {
println("c game start")
}

override fun endPlay() {
println("c game end")
}
}

class Football : Game() {
override fun initialize() {
println("f game end")
}

override fun startPlay() {
println("f game end")
}

override fun endPlay() {
println("f game end")
}

}

Visitor:表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。

fun main(args: Array<String>) {
val computer = Computer()
computer.accept(ComputerPartDisplayer())
}

interface ComputerPart {
fun accept(computerPartVisitor: ComputerPartVisitor)
}

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)
}
}

interface ComputerPartVisitor {
fun visit(computer: Computer)
fun visit(mouse: Mouse)
fun visit(keyboard: Keyboard)
fun visit(monitor: Monitor)
}

class Computer : ComputerPart {

val parts: Array<ComputerPart>

init {
parts = arrayOf(Mouse(), Keyboard(), Monitor())
}

override fun accept(computerPartVisitor: ComputerPartVisitor) {
for (item in parts) {
item.accept(computerPartVisitor)
}
computerPartVisitor.visit(this)
}

}

class ComputerPartDisplayer : ComputerPartVisitor {
override fun visit(computer: Computer) {
println("show computer")
}

override fun visit(mouse: Mouse) {
println("show mouse")
}

override fun visit(keyboard: Keyboard) {
println("show keyboard")
}

override fun visit(monitor: Monitor) {
println("show monitor")
}

}

Filter: 过滤模式

import java.util.*

fun main(args: Array<String>) {
val persons = ArrayList<Person>()
persons.add(Person("watson1", "male", "single"))
persons.add(Person("watson2", "female", "single"))
persons.add(Person("watson3", "male", "married"))
persons.add(Person("watson4", "female", "single"))
persons.add(Person("watson5", "male", "single"))
persons.add(Person("watson6", "female", "married"))

val male = CriteriaMale()
val female = CriteriaFemale()
val single = CriteriaFSingle()
val singleMale = AndCriteria(single, male)

male.meetCriterial(persons).printSelf()
singleMale.meetCriterial(persons).printSelf()
single.meetCriterial(persons).printSelf()
}

class Person(val name: String, val gender: String, val maritalStatus: String) {
}

fun List<Person>.printSelf() {
for (item in this) {
println("item [name:${item.name}] [gender:${item.gender}] [status:${item.maritalStatus}]")
}
println("---")
}

interface Criteria {
fun meetCriterial(persons: List<Person>): List<Person>
}

class CriteriaMale : Criteria {
override fun meetCriterial(persons: List<Person>): List<Person> {
val malePersons = ArrayList<Person>()
for (person in persons) {
if (person.gender == "male") {
malePersons.add(person)
}
}
return malePersons
}
}

class CriteriaFemale : Criteria {
override fun meetCriterial(persons: List<Person>): List<Person> {
val malePersons = ArrayList<Person>()
for (person in persons) {
if (person.gender == "female") {
malePersons.add(person)
}
}
return malePersons
}
}

class CriteriaFSingle : Criteria {
override fun meetCriterial(persons: List<Person>): List<Person> {
val malePersons = ArrayList<Person>()
for (person in persons) {
if (person.maritalStatus == "single") {
malePersons.add(person)
}
}
return malePersons
}
}

class AndCriteria(val criteria: Criteria, val criteria2: Criteria) : Criteria {
override fun meetCriterial(persons: List<Person>): List<Person> {
val firstCriteriaPersons = criteria.meetCriterial(persons);
return criteria2.meetCriterial(firstCriteriaPersons)
}
}

class OrCriteria(val criteria: Criteria, val criteria2: Criteria) : Criteria {
override fun meetCriterial(persons: List<Person>): List<Person> {
val aItems: List<Person> = criteria.meetCriterial(persons)
val bItems: List<Person> = criteria2.meetCriterial(persons)

for (person in bItems) {
if (!aItems.contains(person)) {
aItems.plus(person)
}
}
return aItems
}
}

Null Object :

fun main(args: Array<String>) {
val customer1 = CustomerFactory.getCustomer("Rob")
val customer2 = CustomerFactory.getCustomer("Bob")
val customer3 = CustomerFactory.getCustomer("Julie")
val customer4 = CustomerFactory.getCustomer("Laura")

System.out.println("Customers")
System.out.println(customer1.getName())
System.out.println(customer2.getName())
System.out.println(customer3.getName())
System.out.println(customer4.getName())
}

abstract class AbstractCustomer {
var nameValue: String? = null
abstract fun isNull(): Boolean
abstract fun getName(): String
}

class NullCustomer() : AbstractCustomer() {

override fun isNull(): Boolean {
return true
}

override fun getName(): String {
return "not available in Customer Database";
}
}

class RealCustomer(name: String) : AbstractCustomer() {

init {
nameValue = name
}

override fun getName(): String {
return nameValue ?: ""
}

override fun isNull(): Boolean {
return false
}

}

object CustomerFactory {

val names = arrayOf("watson", "mathilda", "love")

fun getCustomer(name: String): AbstractCustomer {
for (item in names) {
if (item.equals(name)) {
return RealCustomer(name)
}
}
return NullCustomer()
}

}

Composite Entity

fun main(args: Array<String>) {
val client = Client()
client.setData("a", "b")
client.printData()

client.setData("c", "d")
client.printData()
}

class DependentObject1 {
var data: String? = null
}

class DependentObject2 {
var data: String? = null
}

class CoarseGrainedObject {
val do1 = DependentObject1()
val do2 = DependentObject2()

fun setData(data1: String, data2: String) {
do1.data = data1
do2.data = data2
}

fun getData(): Array<String?> {
return arrayOf(do1.data, do2.data)
}
}

class CompositeEntity {
val cgo = CoarseGrainedObject()

fun setData(data1: String, data2: String) {
cgo.setData(data1, data2)
}

fun getData(): Array<String?> {
return cgo.getData()
}
}

class Client {
val compositeEntity = CompositeEntity()

fun printData() {
for (item in compositeEntity.getData()) {
println("data -> " + item)
}
}

fun setData(data1: String, data2: String) {
compositeEntity.setData(data1, data2)
}
}

Front Controller

fun main(args: Array<String>) {
val frontController = FrontController()
frontController.dispatchRequest("Home")
frontController.dispatchRequest("student")
}


class HomeView {
fun show() {
println(" home ")
}
}

class StudentView {
fun show() {
println(" student ")
}
}

class Dispatcher {
val studentView: StudentView
val homeView: HomeView

init {
studentView = StudentView()
homeView = HomeView()
}

fun dispatch(request: String) {
if (request == "student") {
studentView.show()
} else {
homeView.show()
}
}
}

class FrontController {
val dispatcher: Dispatcher

init {
dispatcher = Dispatcher()
}

fun isAuthenticUser(): Boolean {
return true;
}

fun trackRequest(request: String) {
println("page request $request")
}

fun dispatchRequest(request: String) {
trackRequest(request)

if (isAuthenticUser()) {
dispatcher.dispatch(request)
}
}
}

Intercepting Filter

import java.util.*

fun main(args: Array<String>) {
val filterManger = FilterManager(Target())
filterManger.setFilter(AuthenticationFilter())
filterManger.setFilter(DebugFilter())

val client = Client()
client.filterManager = filterManger
client.sendRequest("home")
}

interface Filter {
fun execute(request: String)
}

class AuthenticationFilter : Filter {
override fun execute(request: String) {
println("authenticating request: $request")
}
}

class DebugFilter : Filter {
override fun execute(request: String) {
println("request log: $request")
}
}

class Target {
fun execute(request: String) {
println("Exe request: $request")
}
}

class FilterChain {
val filters: ArrayList<Filter> = ArrayList<Filter>()
lateinit var target: Target

fun addFilter(filter: Filter) {
filters.add(filter)
}

fun execute(request: String) {
for (item in filters) {
item.execute(request)
}
target.execute(request)
}
}

class FilterManager(target: Target) {

val filterChain: FilterChain

init {
filterChain = FilterChain()
filterChain.target = target
}

fun setFilter(filter: Filter) {
filterChain.addFilter(filter)
}

fun filterRequest(request: String) {
filterChain.execute(request)
}
}

class Client {
var filterManager: FilterManager? = null

fun sendRequest(request: String) {
filterManager?.filterRequest(request)
}
}

设计模式的六大原则:

开闭原则:Open Close Principle,对扩展开放,对修改关闭。
里氏代换原则:Liskov Substitution Principle,任何基类可以出现的地方,子类一定可以出现。是对开闭原则的补充。
依赖倒转原则 Dependence Inversion Principle,开闭原则的基础,针对接口编程,依赖于抽象而不依赖于具体。
接口隔离原则 Interface Segregation Principle ,使用多个隔离的接口,比使用单个接口要好。
迪米特法则:Demeter Principle,一个实体应当尽量少的与其他实体之间发生相互作用,使得系统功能模块相对独立。
合成复用原则:Composite Reuse Principle,尽量使用合成、聚合的方式,而不是使用继承。

按照意图将设计模式分为5类

1. 接口型模式:适配器、外观、合成、桥接
2. 指责型模式:单例、观察者、调停者、代理、职责链、享元
3. 构造型模式:构建者、工厂方法、抽象工厂、原型、备忘录
4. 操作型模式:模板方法、状态、策略、命令、解释器
5. 扩展型模式:装饰器、迭代器、访问者

接口型模式

抽象地讲,类的接口是类允许其他类对象访问的方法与字段集。
面向接口的模式适用于需要对一个类或一组类的方法进行定义或重定义的场景。
适配器:适配类的接口以匹配客户端期待的接口
外观:为一组类提供一个简单接口
合成:为单个对象与复合对象提供统一的接口
桥接:接触抽象与实现之间的耦合,使得二者能够独立演化

Adapter 适配器模式:使我们可以重用一个现有的类,当客户端通过接口表达其需求时,通常可以创建一个实现了该接口的新类,同时使该类继承自现有类。当客户端没有指定它所需要的接口时,你就可以使用适配器模式。可能需要创建一个新的客户端类,它将使用现有类的实例。这种方法通过创建一个对象适配器,将客户端的调用指向现有类的实例。如果我们不需要(或许不能)重写客户端可能调用的方法时,这种方式存在一定的危险性。

使用不同接口的类所提供的服务为客户端提供它所期望的接口
扩展不动类,实现需要的接口。
interface RocketSim {
abstract fun getMass(): Double
fun getThrust(): Double
fun setSimTime(t: Double)
}

open class PhysicalRocket(var burnArea: Double,
var burnRate: Double,
var fuelMass: Double,
var totalMass: Double) {

fun getBurnTime(): Double {
return 5.20
}

fun getMass(t: Double): Double {
return 5.20
}

fun getThrust(t: Double): Double {
return 5.20
}
}

class OozinozRocket(burnArea: Double, burnRate: Double, fuelMass: Double, totalMass: Double) :
PhysicalRocket(burnArea, burnRate, fuelMass, totalMass),
RocketSim {

override fun getMass(): Double {
return getMass(1.0)
}

override fun getThrust(): Double {
return getThrust(2.0)
}

override fun setSimTime(t: Double) {
}
}
类的适配器,通过子类进行适配。在类的适配器中,新的适配类实现了需要的接口,并继承自现有类。当你需要适配的一组方法并非被定义在接口中时,这种方式就不奏效了。此时就可以创建一个对象适配器,它使用了委派而非继承。将对象适配为没有明确接口定义的接口。
open class Skyrocket(var mass: Double, var thrust: Double, var burnTime: Double) {

open fun getMassValue(): Double {
return 3.15
}

fun getThrustValue(): Double {
return 3.15
}

fun setSimTime(t: Double) {

}
}

public class OozinozRocket2(mass: Double, thrust: Double, burnTime: Double) : Skyrocket(mass, thrust, burnTime) {
private lateinit var rocket: PhysicalRocket;
val simTime = 0.0

constructor(r: PhysicalRocket) : this(r.getMass(1.0), r.getThrust(1.0), r.getBurnTime()) {
rocket = r
}

override fun getMassValue():Double{
return rocket.getMass(simTime)
}

}
类适配
对象适配
class Rocket {

}

abstract class AbstractTableModel {
abstract fun getColumnCont(): Int
abstract fun getRowCount(): Int
abstract fun getValueAt(position: Int)
}

class ReocketTabModel(val rockets: Array<Rocket>) : AbstractTableModel() {
val columnNames = arrayOf("Name", "Price", "Apogee")

override fun getColumnCont(): Int {
return rockets.size
}

override fun getRowCount(): Int {
return rockets.size * 2
}

override fun getValueAt(position: Int) {
}
}

提供桩实现

MouseListener <--- MouseAdapter

Facade 外观模式:为子系统提供一个接口,便于它的使用。

简化工具包的一种途径。只需少量代码,就能提供典型的、无修饰用法的类库中的类。一个外观就是一个类,它包含的功能介于工具包与完整的应用程序之间,为工具包或子系统的类提供了简单的用法。

Composite 合成模式:为了保证客户端调用对象与组合对象的一致性

1. 组对象允许包含单对象,也可以再包含其他的组对象
2. 要为组合对象和单对象定义共同的行为。

Bridge 桥接模式:将抽象方法的实现相互分离来实现解耦,以便二者可以相互独立地变化。

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.