On Kotlin parsing of design patterns

I. Introduction

Android design patterns is our growth path necessary for a skill, I believe that many students are already Get up, let's look at how design patterns is expressed in Kotlin in it.

Second, singleton

Singleton pattern is a common software design patterns. In its core structure contains only the special class called singleton. Example ensures single mode systems only one instance of a class.

Usage scenarios: Ensure a class has one and only one object of the scene, to avoid multiple objects consume too many resources

  • Java Singleton Review
  • Lazy type:


Starving type:


Kotlin singleton wording

 

kotlin wording is not simply direct him look like a word on the outlines.

Look at the official description

 

 

In Kotlin them directly through keyword to declare a singleton object, and it is thread-safe, and the way object declaration is lazy loading.

Third, the agent mode (mode commissioned)

Proxy mode to provide a proxy for other objects to control access to this object

Proxy mode using a proxy object to access the target object's behavior, the realization of a Kotlin substantially similar to Java

Abstract class


The proxy class

 

 


Acting Class


transfer


Through a proxy model can be determined and complex logic to generate notifications are blocked, so that the code cleaner

 

Fourth, the builder pattern

Construction of the model builder is a complex object and its representation separation, so that the same construction process can create different representations

For example, we used AlertDialog, universal-image-loader is used by the builder pattern, let's look at how to express in kotlin

 


Use the same method with Java


In fact, Kotlin apply the extension also supports native mode Builder

 

 

Fifth, the Observer pattern

It is dependent on the observer model defining the relationships between objects of one kind-many, so that changes state whenever an object, all objects that depend on it are notified and updated automatically

Common mode observer as notifyDataSetChanged update method of the Adapter RecyclerView, BroadcastReceiver, open source library EventBus, RxJava etc.

Kotlin wording similar to Java

To achieve global management observed by a single embodiment unread messages UnReadMessageObserver


The observed


Observer

 

观察者模式是我们经常使用的模式,它的一个重要作用就是解耦,将观察者个被观察者解耦

六、适配器模式

1.适配器模式把一种接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作
2.举个栗子:手机普通充电需要5V的电压,而生活用电电压是220V,而我们的充电器就充当了转换适配的作用,
3.这里的适配器也是一个道理
4.适配器模式中的目标接口也就是 5V电压的接口

 


适配器模式中需要被适配的接口,日常220V电压


适配器

 

以上就是适配器模式在Kotlin上的简单实现了,适配器模式的原理在于把原本不兼容的接口融合在了一起,使之能更好的协作。

总结

以上几种设计模式是我们经常会用到的,Kotlin的大多设计模式基本与Java实现大致相同,灵活的使用设计模式能让我们代码更加的灵活,便于管理。

关于我

更多信息可以点击关于我 , 非常希望和大家一起交流 , 共同进步
 目前是一名程序员,不仅分享 Android开发相关知识,同时还分享技术人成长历程,包括个人总结,职场经验,面试经验等,希望能让你少走一点弯路。

Guess you like

Origin www.cnblogs.com/1157760522ch/p/11670740.html