关于设计模式很对开发者都知道很重要,但陆陆续续学习过不少次,但学过的设计模式也基本忘了差很少,能记住的仍是以前使用的几个基本的,如今借此机会将23 中设计模式完整的梳理学习下,Java设计模式分类:java
建立型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。git
结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。程序员
行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式github
本篇全部的实例代码和uml图地址:JavaDesignModule算法
Factory Method模式原理来自意见产品的生产过程,从定义上的理解,将某一类事物按照面向对象的思想抽取成产品类,而后建立对应的工厂按照固定的模式建立相应的产品,至关于工厂里的产品生产线,通常使用工厂模式时都伴随着类似功能的类,这里的工厂模式也主要是根据条件建立正确的类;编程
interface Product {
fun action()
}
class Car(val name : String) : Product { // 具体的产品类
override fun action() {
Log.e("Car -------- ","$name 是私家车!本身驾驶!")
}
}
复制代码
interface ProductFactory {
fun createProduct(name: String):Product //建立Product抽象方法 } open class CarFactory : ProductFactory { // 具体的工厂类
override fun createProduct(name: String): Product {
return Car(name)
}
}
复制代码
val car = CarFactory().createProduct("Audi") //建立具体工厂类,并调用方法建立产品
car.action()
复制代码
意义 工厂模式利用抽象产品的转型和统一管理产品的建立,将全部的实际产品和使用这些产品的代码解耦,有利于代码的扩展和维护设计模式
使用场景缓存
简介 上面的工厂方法模式只是只针对单一类的产品,而对于多个产品时,若是继续使用工厂模式则势必要工厂类,这违背了开闭原则,此时须要使用抽象工厂模式,将工厂抽象出来,在工厂接口中定义多个产品的生产方法,而后让每一个具体的工厂分别生产本身对应的一个或多个产品,从而造成不一样的工厂群和各自产品线的形式;数据结构
使用实例框架
abstract class Computer{
abstract fun action() } abstract class Phone(var name: String = "Phone") {
abstract fun call(number : String) } 复制代码
class ComputerGreen : Computer() { // 电脑
override fun action() {
System.out.println(" Action by Green Computer !")
}
}
class PhoneGreen : Phone() { // 手机
override fun call(number: String) {
System.out.println(" Call $number by Green Phone !")
}
}
class ComputerRed : Computer() {
override fun action() {
System.out.println(" Action by Red Computer !")
}
}
class PhoneRed : Phone() {
override fun call(number: String) {
System.out.println(" Call $number by Red Phone !")
}
}
复制代码
interface Factory {
fun createComputer() : Computer//生产电脑 fun createPhone() : Phone // 生产手机 } 复制代码
class FactoryGreen : Factory {
override fun createComputer(): Computer {
return ComputerGreen() //生产Green电脑
}
override fun createPhone(): Phone {
return PhoneGreen() //生产Green手机
}
}
class FactoryRed : Factory {
override fun createComputer(): Computer {
return ComputerRed() //生产Red电脑
}
override fun createPhone(): Phone {
return PhoneRed() //生产Red手机
}
}
复制代码
val factoryGreen = FactoryGreen() // 建立Green工厂
factoryGreen.createComputer()
factoryGreen.createComputer()
val factoryRed = FactoryRed() // 建立Red工厂
factoryRed.createComputer()
factoryRed.createComputer()
复制代码
简介 单例模式是开发中常用的基本模式,尤为在一些工具类或框架的初始化中,如:Glide、EventBus等,它的最主要特性就是确保通常状况下程序中只有一个实例;
功能角色
使用实例
class Singleton private constructor() {
companion object {
var singleton: Singleton? = null fun getIntance(): Singleton {
if (singleton == null) {
synchronized(Singleton::class.java) {
singleton = Singleton()
}
}
return singleton!!
}
}
}
复制代码
class SingletonInner private constructor() {
class SingleHolder {
companion object {
val singletonInner = SingletonInner()
}
}
}
复制代码
val single = Singleton.getIntance()
val singleInner = SingletonInner.SingleHolder.singletonInner
复制代码
Builder设计模式是不少人第一个接触的设计模式,就基本的Dialog就是使用Builder完成初始化,它利用在建立实例前使用Builder设置和保存配置的方式,极大的丰富了对象的使用场景和配置,并且使用中造成了链式调用;
功能角色 
使用实例:参见AlertDialog的使用
意义:简化并统一对象的初始化过程,丰富对象的使用场景
使用场景 对于某个功能基本使用相同,但场景变化很是多时可使用Builder模式,将具体和功能和变换的配置解耦;
简介 原型模式,从名称的中就能大概读出他的意思,它是利用已有的对象直接克隆出新对象,至关于自己的复制版,从而避免一系列的初始化和建立工做,而且能够保持和现有对象彻底同样的数据,对于原型自己须要具备调用clone()方法的能力,通常实现Cloneable接口便可;
功能角色
open class BaseProduct : Cloneable {
var name: String? = null
var price = 0
}
class CarProduct : BaseProduct(){
var coclor = "红色"
fun createClone(): CarProduct { // 提供克隆方法
return super.clone() as CarProduct // 克隆并转换对象
}
}
复制代码
class FoodProduct(var food: Food) : BaseProduct(){
fun createClone(): FoodProduct {
val product = super.clone() as FoodProduct
product.food = food.createClone()// 内部存储的对象也须要克隆并赋值
return product
}
}
复制代码
open class Food( var price: Int = 0, var shop: String = "Shop" ) : Cloneable{ //由于浅复制的缘由,Food也要实现Cloneable而且提供复制方法
fun createClone(): Food {
return super.clone() as Food
}
}
复制代码
val car = CarProduct()
car.name = "Audi"
car.price = 10000
val cerClone = car.createClone() // 克隆对象
Log.e("Car Name ---",cerClone.name)
Log.e("Car Price ---",cerClone.price.toString())
Log.e("Car Color ---",cerClone.coclor)
复制代码
对于适配器咱们接触作多的就是电源适配器,对于咱们身边的电源通常都提供的是220V交流电,但不一样的电器设备所需的电压不一样,那如何让它们正常使用呢?这就须要适配器的存在,它能够将200V的电压转换为各自须要的电压,并且不一样的国家之间提供的电源也不一样,那么常常出差的人员可能就会配备多种不一样的适配器,但它们的做用只有一个将现有不可直接使用的转换为可用的;
一样的道理也适应在程序中,若是给你一个写好的工具类,须要将它使用在其余程序上,固然若是能直接使用最好,若是不能就须要在两者之间构建适配器
假设目前只有一个输出Int类型的工具类PrintInt,而提供的数据源是String类型,如今须要用适配器去让PrintInt能够执行;
open class PrintInt {
protected fun printInt(number : Int){
Log.e("输出数字","number = $number")
}
}
复制代码
interface PrintString {
fun print(message : String)// 声明方法传入字符串 } 复制代码
class Adapter : PrintString ,PrintInt(){
override fun print(message : String) { //重写方法
when(message){
"123" -> {printInt(123)}//将输入的字符串调用printInt()输出
}
}
}
复制代码
val adapter = Adapter()
adapter.print("123")
复制代码
假设如今有一个功能是按照行和列输出字符串,如今有个需求要在输出的字符串上下左右添加边框,在不改变原来程序的基础上使用装饰者模式实现
abstract class Component {
abstract fun getRows(): Int // 获取字符串行数 abstract fun getColumns(): Int // 获取字符串列数 abstract fun getTextByRow(number: Int): String // 获取对应的字符串 fun show() { // 显示内容
val rows = getRows()
for (index in 0 until rows) {
System.out.println(getTextByRow(index))
}
}
}
复制代码
class ConcerteComponent(val text: String) : Component() {
override fun getRows() = 1
override fun getColumns(): Int {
return text.length
}
override fun getTextByRow(number: Int): String {
return text
}
}
复制代码
abstract class Decorator (val component: Component) : Component() 复制代码
class ConcerteDecorator constructor(component: Component) : Decorator(component) {
override fun getRows(): Int {
return component.getRows() + 2
}
override fun getColumns(): Int {
return component.getColumns() + 2
}
override fun getTextByRow(number: Int): String {
return when (number) {
0 -> {"----------"}
getRows() - 1 -> {"----------"}
else -> {
"| ${component.getTextByRow(number)} |"
}
}
}
}
复制代码
从上面的包装类看出,它继承了一样的抽象类实现了一样的抽象接口,在重写的方法中主体仍是调用被包装对象方法,而后在返回结果上增长处理;
val component = ConcerteComponent("HELLO")
val concerteDecorator = ConcerteDecorator(component)
concerteDecorator.show()
复制代码
意义:更容易扩展原有程序的功能,而无需修改或影响原有程序
使用场景:当须要拓展某个对象功能时,且包装对象和被包装对象具备一致性时使用装饰着模式进行扩展
代理模式是使用一个类似的对象来替代真实的对象,从而实现一系列的功能修改,比如现实中的中介代理同样,当你须要某种需求时直接找代理,它们会帮你完成功能的实现;
interface PrintInterface { // 接口方法
fun setName(name: String) fun getName(): String fun print(content: String) } // 原有实现的功能方法 class RealPrint(private var nameReal: String) : PrintInterface {
override fun setName(name: String) {
action()
nameReal = name
}
override fun getName(): String {
action()
return nameReal
}
override fun print(content: String) {
Log.e("RealPrint = ", content)
}
private fun action(){}
}
复制代码
如今已经有一个接口和对应实现的工具类RealPrint,但在RealPrint中的set和get两个方法中每次都会调用额外的action()方法,如今的需求是要使用此类但又不要作额外的工做,此时使用代理模式修改set和get方法
class ProxyPrint( private var nameProxy: String) : PrintInterface {
private var realPrint: RealPrint? = null
override fun setName(name: String) {
realPrint?.setName(name)
nameProxy = name
}
override fun getName(): String {
return nameProxy
}
override fun print(content: String) {
initRealPrint()
realPrint?.print(content)
}
private fun initRealPrint() {
if (realPrint == null) {
realPrint = RealPrint(nameProxy)
}
}
}
复制代码
在代理类ProxyPrint一样继承方法接口,并且内部保存着真实对象,在代理中修改了setName()和getName()方法,删除调用的action()对象,在print()中由于要用到代理类的方法,因此建立代理类对象;
当某个工具类或方法须要修改时,为了避免违反开闭原则可使用代理模式,将方法的修改部分和原始部分分离,互不影响;
外观模式主要的功能解决类之间的依赖关系,以面向对象的思想编程,会将某个对象的功能方法封装在一块儿,但又是一个程序或模块的执行须要依赖相关联的介个类,那为了避免让类之间出现耦合就可采用外观模式处理类的关系,从而实现类的解耦;
class Dashboard {
fun start() {
System.out.println("仪表盘启动!")
}
fun stop(){
System.out.println("仪表盘中止!")
}
}
class Engine {
fun start() {
System.out.println("发动机启动!")
}
fun stop(){
System.out.println("发动机中止!")
}
}
复制代码
class Car() {
private var dashboard: Dashboard = Dashboard()
private var engine: Engine = Engine()
fun start() {
engine.start()
dashboard.start()
}
fun stop() {
engine.stop()
dashboard.stop()
}
}
复制代码
val car = Car()
car.start()
car.stop()
复制代码
简介 桥接模式就是把使用和其具体实现分开,使他们能够各自独立的变化。桥接的用意是:将抽象化与实现化解耦,使得两者能够独立变化,实际是将代码的功能层次结构和实现层次结构相分离(这两个概念后面会介绍)
功能角色
interface Implementer {
fun action(msg: String) fun print(msg: String) } class PrintImplementer : Implementer{
override fun action(msg: String) {
System.out.println(" Print Action = $msg")
}
override fun print(msg: String) {
System.out.println(" Print Print= $msg")
}
}
复制代码
val implementer: Implementer = PrintImplementer() // 内部建立对象
fun action(msg: String) {
implementer.action(msg) // 调用真实实现的方法
}
fun print(msg: String) {
implementer.print(msg)
}
}
复制代码
class AddFunction:Function() {
fun doSomething(msg: String) { // 外观模式
action(msg)
print(msg)
}
}
复制代码
简介 组合模式定义:可以使容器和内容具备一致性,创造出递归结构的模式,可能定义比较抽象,它主要想形容一种数据结构,你可把它想像成文件和文件夹同样,将文件夹当成容器,文件夹里面便可以放文件也能够放文件夹,此时就是容器和内容一致;
功能角色
使用实例:以文件夹结构为例
abstract class Entry {
var parent: Entry? = null // 父文件夹
var name: String? = null //文件名称
abstract fun getSize(): Int // 文件大小 abstract fun getAbslouteName() : String? // 文件路径 abstract fun printStrign( msg: String) // 输出信息 } 复制代码
class Directory(val nameFile: String, val parentFile: Entry? = null) : Entry() {
private val arrayList = ArrayList<Entry>() // 保存容器内部文件
init {
name = nameFile
parent = parentFile
}
override fun getSize(): Int { // 遍历获取文件夹大小
val iterator = arrayList.iterator()
var size = 0
while (iterator.hasNext()){
size += iterator.next().getSize()
}
return size
}
override fun printStrign(msg: String) {
val iterator = arrayList.iterator()
while (iterator.hasNext()){
iterator.next().printStrign("$msg / $name")
}
}
override fun getAbslouteName(): String? {
if (parentFile == null) {
return name
}
return parentFile.getAbslouteName() +"/"+ name
}
fun add(entry: Entry) { // 向文件夹内添加文件
entry.parent = this
arrayList.add(entry)
}
}
复制代码
class File(val nameFile: String, val sizeFile: Int = 0, var parentFile: Entry? = null) : Entry() {
override fun printStrign(msg: String) {
Log.e("======","$msg / $name")
}
override fun getAbslouteName(): String? {
if (parent == null) {
return name
}
return parent!!.getAbslouteName() +"/"+ name
}
init {
name = nameFile
parent = parentFile
}
override fun getSize(): Int = sizeFile
}
复制代码
val rootD = Directory("root") // 建立跟目录
val bin = Directory("bin",rootD) // 建立二级文件夹
val tem = Directory("tem",rootD)
val user = Directory("user",rootD)
val vi = File("vi",1000) // 建立文件
val latex = File("latex",500)
val tem_in = File("latex",800)
rootD.add(bin) // 添加文件
rootD.add(tem)
rootD.add(user)
bin.add(vi)
bin.add(latex)
tem.add(tem_in)
bin.add(tem)
复制代码
简介 享元模式:主要是利用缓存对象的方式实现对象的共享,从而减小对象的建立,在开发中也很常见,一般与Factory一块儿使用,经过工厂产生数据前会线查看缓存信息,若是有则直接返回不然建立新对象并缓存;
功能角色
使用实例:JDBC链接池
意义:避免了对象的屡次建立,提升程序的总体性能
使用场景:每次使用都须要建立对象时,避免屡次建立可使用Flyweight模式
interface Iterator {
/** * 判断是否有下一条数据 */
fun hasNext(): Boolean /** * 根据下标遍历获取数据 */ fun next() : Any } interface Congregation {
/** * 初始化迭代器 */
fun createIterator():Iterator } 复制代码
class StudentIterator(private val congregation: StudentCongregation) : Iterator {
var index = 0
override fun hasNext(): Boolean {
return index < congregation.getSize()
}
override fun next(): Student {
val student = congregation.get(index)
index++
return student
}
}
复制代码
class StudentCongregation : Congregation {
private val list by lazy { arrayListOf<Student>()}
override fun createIterator(): StudentIterator { // 建立具体的迭代器
return StudentIterator(this)
}
fun getSize():Int{
return list.size
}
fun add(student: Student){
list.add(student)
}
fun get(index : Int): Student{
return list[index]
}
}
复制代码
val congregation = StudentCongregation()
for (id in 0..5) {
congregation.add(Student(id,"name = id",id * 10))
}
val iterator = congregation.createIterator()
while (iterator.hasNext()){
val student = iterator.next()
Log.e("=====","id = ${student.id} name = ${student.name} age = ${student.age}")
}
复制代码
简介 策略模式:对于某个需求时咱们可能会使用一些算法或逻辑来解决,但由于不一样原用需求中算法须要被总体改变或替换时,通常的编程方式可能很难实现,但若是将每一个固定的逻辑封装成策略,将它与总体系统分离,在执行须要时传入对应的策略,此时逻辑就好像一个固定的模块功能,便可实现无限次数的替换;
功能角色
使用实例
interface Strategy {
fun actionStrategy(number: Int): Int // 声明的策略方法 } 复制代码
class NumberStrategy : Strategy { // 第一种策略
override fun actionStrategy(number: Int): Int {
Log.e(" NumberStrategy = ", number.toString())
return number
}
}
class DoubleStrategy : Strategy { // 第二种策略
override fun actionStrategy(number: Int): Int {
return number * number
}
}
复制代码
val player = Palyer(NumberStrategy())
player.play(5)
val playerD = Palyer(DoubleStrategy())
playerD.play(5)
复制代码
简介 模版模式:即全部的实现按照统一的方式进行,这里统一的方式指固定的执行逻辑,模版模式首先在父类中借助抽象方法实现逻辑的调用顺序,而后在不一样的子类中处理具体的抽象方法便可;
功能角色
使用实例:以公司职员一天的工做为例
abstract class AbstractTemplate {
protected abstract fun weakUp() //起床以后的事情 protected abstract fun enteringTheOffice() //进入办公室 protected abstract fun openCompute() //打开电脑 protected abstract fun doJob() //工做 protected abstract fun goHome() //回家 fun actionForWorker() { // 方法中肯定了执行的逻辑
weakUp()
enteringTheOffice()
openCompute()
doJob()
goHome()
}
}
复制代码
class DesignWorker(val name: String) : AbstractTemplate() { // 设计师工做
override fun weakUp() {
Log.e("$name ------","8:00 起床了!")
Log.e("$name ------","8:10 刷牙洗脸!")
Log.e("$name ------","8:20 健身!")
Log.e("$name ------","8:40 吃早饭!")
Log.e("$name ------","9:00 开车出发!")
}
override fun enteringTheOffice() {
Log.e("$name ------","9:30 进入公司!")
Log.e("$name ------","9:35 泡了杯咖啡!")
}
override fun openCompute() {
Log.e("$name ------","9:40 看了场设计秀!")
}
override fun doJob() {
Log.e("$name ------","10:30 开始设计!")
}
override fun goHome() {
Log.e("$name ------","7:00 开车回家!")
}
}
class ITWorker(val name: String) : AbstractTemplate() { // 程序员工做
override fun weakUp() {
Log.e("$name ------","8:30 起床了!")
Log.e("$name ------","9:00 刷牙洗脸,出发上班了!")
}
override fun enteringTheOffice() {
Log.e("$name ------","9:30 进入公司!")
Log.e("$name ------","9:35 接了杯白开水!")
}
override fun openCompute() {
Log.e("$name ------","9:40 打开它的Mac Pro !")
}
override fun doJob() {
Log.e("$name ------","9:40 开始一天的写代码 !")
}
override fun goHome() {
Log.e("$name ------","7:00 开始下班坐地铁回家 !")
}
}
复制代码
val itWorker = ITWorker("程序猿")
val design = DesignWorker("设计师")
itWorker.actionForWorker()
design.actionForWorker()
复制代码
设计模式意义 模版模式的优势在于只需在父类中编写算法和处理流程,子类中无需编写只需关注自身细节的处理,分离了总体逻辑和实现,提升代码的可读性也极大简化了程序的修改和维护;
使用场景:像例子同样按照总体逻辑但针对不一样的目标处理时,便可采用模版模式定义实现模版,而后各自实现细节
interface Visitor {
fun visitor(file: FileElement) fun visitor(directory: DirectoryElement) } class ConcreteVisitor : Visitor {
override fun visitor(file: FileElement) {
Log.e("File=======", file.name)
}
override fun visitor(directory: DirectoryElement) {
Log.e("Directory=======", directory.name)
val iterator = directory.getInterator() // 对于文件夹循环遍历内部文件
while (iterator.hasNext()) {
val file = iterator.next()
file.accept(this)
}
}
}
复制代码
abstract class Element {
var parent: Element? = null
var name: String? = null abstract fun accept(visitor: Visitor) } 复制代码
class FileElement(val nameFile: String, val sizeFile: Int = 0, var parentFile: Element? = null) : Element() { //File
override fun accept(visitor: Visitor) {
visitor.visitor(this)
}
init {
name = nameFile
parent = parentFile
}
}
class DirectoryElement(val nameFile: String, val parentFile: Element? = null) : Element() { //Directory
override fun accept(visitor: Visitor) {
visitor.visitor(this)
}
val arrayList = ArrayList<Element>()
init {
name = nameFile
parent = parentFile
}
fun add(entry: Element) {
entry.parent = this
arrayList.add(entry)
}
fun getInterator() = arrayList.iterator()
}
复制代码
意义 访问模式实现了数据结构和数据访问的分离,对于数据结构稳定但访问算法常常改变的场景,此时使用访问模式分离可变的处理逻辑,更好的体现了开闭原则;
使用场景:数据结构稳定,但对数据的访问和处理逻辑常常改变的场景
简介 观察者模式也是开发中常常接触和使用的设计模式之一,在开源框架和Android系统组件中都有使用,典型表明RxJava、LiveData等;它的逻辑也很简单主要将事件产生对象做为被观察者,将处理事件的逻辑做为观察者,两者采用注册或订阅的方式关联,当事件发送时调用观察者的方法处理事件;
功能角色
使用实例:RxJava(Android框架源码分析——RxJava源码分析)
意义 将整个逻辑的处理分为观察者和被观察者两部分,被观察者只需发送事件无需知道谁观察则本身,而观察者只需处理事件也无需知道事件的来源,此时被观察者和观察者能够任意组合使用;
使用场景:须要都某个过程实现订阅,当有新的消息通知自动处理时使用观察者;
简介 命令模式:将任务的执行向命令传递同样发送,由指挥官发送命令,通过系列的传达后到达目标士兵,士兵接收命令后执行,从这里看出指挥官不必定知道他的命令最终通过多少传递和由谁执行,它只须要知道本身要下达那条命令,而士兵可能也不知道他的任务最初是谁的想法和命令,因此在程序中以此方式分离的发送命令和执行命令的角色;
功能角色
使用实例
interface Command {
fun action() } 复制代码
class Receiver {
fun doAction(){......}
}
class ActionCommand(private val receiver: Receiver) : Command {
override fun action() {
receiver.doAction()
}
}
复制代码
class Invoke(private val command: Command) {
fun doInvoke() {
command.action()
}
}
复制代码
val receiver = Receiver()
val command = ActionCommand(receiver)
val invoke = Invoke(command)
invoke.doInvoke()
复制代码
意义 将命令发送者和执行者分离实现代码解耦,在使用时能够为每条命令选择相应的执行者和发送者;
使用场景:对于请求和执行相分离的场景
class Memento(val money : Int) // 内部保存钱数
复制代码
class User {
private var money = 0
private var memento: Memento = Memento(money)
fun getMemory() {
money = Random().nextInt()
}
fun createMementoInfo() { // 保存
memento = Memento(money)
}
fun restoreMementoInfo() { // 恢复
money = memento.money
}
}
复制代码
abstract class Support {
private var next: Support? = null fun setNextSupport(support: Support): Support? { //设置下一个职责对象
next = support
return next
}
abstract fun action(number: Int) // 执行具体的操做 abstract fun canResolve(number: Int): Boolean // 判断是否符合执行条件 fun doAction(number: Int) {
if (canResolve(number)) {
action(number)
} else if (next == null) {
doFailed()
} else {
next?.doAction(number)
}
}
fun doFailed() { // 当没有方法处理时
System.out.println("No Support")
}
}
复制代码
class SupportFirst : Support() {
override fun action(number: Int) {
System.out.println("SupportFirst")
}
override fun canResolve(number: Int): Boolean {
return number < 10
}
}
class SupportSecond(val numberMax : Int) : Support() {
override fun action(number: Int) {
System.out.println("SupportFirst")
}
override fun canResolve(number: Int): Boolean {
return number in 10..numberMax
}
}
复制代码
val supportFirst = SupportFirst() // 建立职责对象
val supportSecond = SupportSecond(20)
val supportThird = SupportSecond(30)
supportFirst.setNextSupport(supportSecond).setNextSupport(supportThird) //设置职责链
supportFirst.action(25) // 调用方法
复制代码
意义:经过使用多个职责对象造成责任链的形式,弱化了发送请求对象和处理请求对之间的关系,对于每一个职责类来看,只须要关注自身的职责即处理条件和处理方式,而整个职责链的设置和调用顺序也能够随时修改和增减;
使用场景:当须要针对多种条件分别处理逻辑时使用职责模式;
简介 状态模式很好理解,对象的自己可能会有多种状态存在,处在不一样的状态时对象的属性和操做都有所不一样,状态模式就是指针对当前状态下的全部操做进行编程,而后在使用时根据具体状况切换状态便可
功能角色
使用实例:以开关等为例
interface State {
fun openLight(light: Light) // 开灯 fun closeLight(light: Light) // 关灯 } 复制代码
class StateClose : State { // 关灯状态
companion object {
val close = StateClose()
}
override fun openLight(light: Light) {
light.isLight = true
System.out.println("打开灯了")
light.steState(StateOpen.open)
}
override fun closeLight(light: Light) {
System.out.println("灯还没开")
}
}
class StateOpen : State { // 开灯状态
companion object {
val open = StateOpen()
}
override fun openLight(light: Light) {
System.out.println("灯已经开了")
}
override fun closeLight(light: Light) {
light.isLight = false
System.out.println("灯关闭了")
light.steState(StateClose.close)
}
}
复制代码
class Light {
var isLight = false
private var state: State = StateClose.close fun steState(state: State) {
this.state = state
}
fun open() {
state.openLight(this)
}
fun close() {
state.closeLight(this)
}
}
复制代码
val light = Light()
light.open()
light.open()
light.close()
light.close()
复制代码
意义:使用状态模式,将全部的操做以不一样的状态呈现,在每次操做完成后修改当前状态,避免了每一个操做中都须要大量的条件判断,提升程序的可读性和扩展性
使用场景:针对不一样状态有不一样操做的场景
class First : Action {
override fun action() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
class Second : Action {
override fun action() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
复制代码
class Meidator {
val first = First()
val second = Second()
fun doAction() {
first.action()
second.action()
}
}
复制代码
val meidator = Meidator()
meidator.doAction()
复制代码
意义:将类之间的依赖关系解耦,提升程序的可维护性
使用场景:当现有的工具或代码不能单独实现逻辑时,此时使用中介者模式组合使用代码,在中介者中实现代码调用;
到此Java中的23种设计模式就介绍完毕了,对设计模式的学习相信不少人的感触都是一致的,学习的时候发现设计模式很奇妙,也确实颇有设计感,但真正使用时仍是不太容易正确的选择和使用,这也是对设计模式的理解不够深刻吧,但愿经过此23 中设计模式的学习能更好的掌握并使用设计模式;