其他
Kotlin学习之设计模式篇
本文字数:6938字
预计阅读时间:52分钟
private static SingletonJ mInstance = new SingletonJ();
private SingletonJ(){
}
public static SingletonJ getInstance(){
return mInstance;
}
public void doTest(){
System.out.println("test singleton java");
}
}
fun doTest(){
println("test singleton kotlin")
}
}
public static final SingletonK INSTANCE;
public final void doTest() {
String var1 = "test singleton kotlin";
boolean var2 = false;
System.out.println(var1);
}
private SingletonK() {
}
static {
SingletonK var0 = new SingletonK();
INSTANCE = var0;
}
}
private volatile static SingleDoubleCheckJava instance;
private SingleDoubleCheckJava() {
}
public static SingleDoubleCheckJava getInstance() {
if (instance == null) {
synchronized (SingleDoubleCheckJava.class) {
if (instance == null) {
instance = new SingleDoubleCheckJava();
}
}
}
return instance;
}
}
companion object {
val instance: SingletonDubbleCheckKotlin by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
SingletonDubbleCheckKotlin() }
}
fun doTest(){
println("test singleton SingletonDubbleCheckKotlin")
}
}
when (mode) {
LazyThreadSafetyMode.SYNCHRONIZED -> SynchronizedLazyImpl(initializer)
LazyThreadSafetyMode.PUBLICATION -> SafePublicationLazyImpl(initializer)
LazyThreadSafetyMode.NONE -> UnsafeLazyImpl(initializer)
}
private var initializer: (() -> T)? = initializer
@Volatile private var _value: Any? = UNINITIALIZED_VALUE
// final field is required to enable safe publication of constructed instance
private val lock = lock ?: this
override val value: T
get() {
val _v1 = _value
if (_v1 !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST")
return _v1 as T
}
return synchronized(lock) {
val _v2 = _value
if (_v2 !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST") (_v2 as T)
} else {
val typedValue = initializer!!()
_value = typedValue
initializer = null
typedValue
}
}
}
* Represents a value with lazy initialization.
*
* To create an instance of [Lazy] use the [lazy] function.
*/
public interface Lazy<out T> {
/**
* Gets the lazily initialized value of the current Lazy instance.
* Once the value was initialized it must not change during the rest of lifetime of this Lazy instance.
*/
public val value: T
/**
* Returns `true` if a value for this Lazy instance has been already initialized, and `false` otherwise.
* Once this function has returned `true` it stays `true` for the rest of lifetime of this Lazy instance.
*/
public fun isInitialized(): Boolean
}
public inline operator fun <T> Lazy<T>.getValue(thisRef: Any?, property: KProperty<*>): T = value
interface Fruit {
void showPrice();
}
//AbsFruit.java
abstract class AbsFruit implements Fruit {
public float mPrice;
}
//Apple.java
class Apple extends AbsFruit {
Apple(float price){
mPrice = price;
}
@Override
public void showPrice() {
System.out.println(" apple price is " + mPrice);
}
}
//Banana.java
class Banana extends AbsFruit {
Banana(float price){
mPrice = price;
}
@Override
public void showPrice() {
System.out.println(" banana price is " + mPrice);
}
}
//FruitFactory.java
class FruitFactory {
public static Fruit getApple(){
return new Apple(5.0f);
}
public static Fruit getBanana(){
return new Banana(8.0f);
}
public static void main(String[] args) {
Fruit apple = FruitFactory.getApple();
apple.showPrice();
}
}
val price : Float
fun showPrice()
}
class FruitFactory{
companion object{
fun getApple() : FruitInKotlin = AppleInKotlin(5.0f)
fun getBanana() : FruitInKotlin = BananaInKotlin(8.0f)
}
}
class AppleInKotlin (override val price: Float) : FruitInKotlin{
override fun showPrice() {
println(" apple in kotlin price is $price")
}
}
class BananaInKotlin (override val price: Float) : FruitInKotlin{
override fun showPrice() {
println(" banana in kotlin $price")
}
}
fun main() {
val apple = FruitInKotlin.getApple()
apple.showPrice()
}
2、工厂方法
fun getFruit() : FruitInKotlin
}
class AppleFactory : AbsFruitFactory{
override fun getFruit(): FruitInKotlin = AppleInKotlin(5.0f)
}
fun main() {
val appleFactory = AppleFactory()
val fruit = appleFactory.getFruit()
}
fun main() {
val apple = FruitFactory.getApple()
apple.showPrice()
val orange = FruitFactory.getOrange()
orange.showPrice()
}
fun main() {
val redCar = Car(color="red"); //不关心汽车品牌,只关心颜色
val bmwCar = Car(factory = "BMW")//不关心颜色,只关心品牌
}
var color : String = "black"
var factory : String = "Audi"
}
fun main() {
val newCar = Car().apply {
factory = "BMW"
color = "red"
}
}
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}
fun main() {
val imageList = arrayOf("1.png","2.png","3.png")
val document1 = Document("aaaaaa",imageList);
val document2 = document1.copy(text = "bbbbb")
}
fun draw()
}
class Circle : Shape{
override fun draw() {
println("draw Circle")
}
}
fun Shape.redColor(decorator : Shape.() -> Unit) {
println("with red color extend")
decorator()
}
fun Shape.boldLine(decorator : Shape.() -> Unit) {
println("with bold line extend")
decorator()
}
fun main() {
Circle().run {
boldLine {
redColor {
draw()
}
}
}
}
fun draw()
fun prepare()
fun release()
}
class Circle : Shape{
override fun draw() {
println("draw Circle")
}
override fun prepare() {
println(" prepare Circle")
}
override fun release() {
println(" release Circle")
}
}
class RedShapeKotlin(val shape : Shape) : Shape by shape{
override fun draw() {
println("with red color by ")
shape.draw()
}
}
class BoldShapeKotlin(val shape : Shape) : Shape by shape{
override fun draw() {
println("with bold line by")
shape.draw()
}
}
fun main() {
val circle = Circle()
val decoratorShape = BoldShapeKotlin(RedShapeKotlin(shape = circle))
decoratorShape.draw();
}
fun NewerDisCount(money : Int) : Int{ return money/2 }
class Customer(val discount : (Int)->Int){
fun caculate( money : Int) : Int{
return discount(money)
}
}
fun main() {
val newCustomer = Customer(::NewerDisCount)
newCustomer.caculate(1000);
val fullDiscountCustomer = Customer(::fullDisCount)
fullDiscountCustomer.caculate(300)
}
caculatePrice()
pay()
sendHome()
}
private fun sendHome(){
println("send home!")
}
private fun caculatePrice(){
println("caculate price!")
}
fun zfbPay(){println("pay by ZFB")}
var shopping = OnlineShopping()
shopping.submitOrder { weixinPay() }
shopping.submitOrder { zfbPay() }
}
private List<User> observers = new ArrayList<>();
void addOberver(User user){
this.observers.add(user);
}
void deleteObserver(User user){
this.observers.remove(user);
}
void notifyUsers (String vid){
for(User user : observers){
user.update(this,user.name + "_" + vid);
}
}
}
class User implements Observer {
String name;
User(String name){
this.name = name;
}
@Override
public void update(Observable observable, Object o) {
System.out.println(o);
}
}
public static void main(String[] args) {
VideoObserverable videoUpdates = new VideoObserverable();
videoUpdates.addOberver(new User("Allen"));
videoUpdates.addOberver(new User("Bob"));
videoUpdates.notifyUsers("101");
videoUpdates.notifyUsers("102");
}
fun update(message:String)
}
class VideoObserverableInKotlin {
var observers: MutableList<UserInKotlin> = ArrayList()
var vid: Int by Delegates.observable(0) { _, old, new ->
observers.forEach{
it.update("${it.name}_$vid")
if (old==new) it.update(" no new value")
else it.update("${it.name}_$vid")
}
}
}
class UserInKotlin(val name: String) : VideoUpdateListener {
override fun update(message:String) {
println(message)
}
}
fun main(args: Array<String>) {
val videoUpdates = VideoObserverableInKotlin()
videoUpdates.observers.add(UserInKotlin("Allen"))
videoUpdates.observers.add(UserInKotlin("Bob"))
videoUpdates.vid=101
videoUpdates.vid=102
}
Delegates.observable
,该函数有两个参数,接受一个初始值,和一个属性改变后的回调函数,回调函数有三个参数,第一个是被赋值的属性,第二个是旧值,第三个是新值。开发者可以根据自己的需求,实现属性改变后的逻辑。我们看一下Delegates的源码* Returns a property delegate for a read/write property that calls a specified callback function when changed.
* @param initialValue the initial value of the property.
* @param onChange the callback which is called after the change of the property is made. The value of the property
* has already been changed when this callback is invoked.
*
* @sample samples.properties.Delegates.observableDelegate
*/
public inline fun <T> observable(initialValue: T, crossinline onChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Unit):
ReadWriteProperty<Any?, T> =
object : ObservableProperty<T>(initialValue) {
override fun afterChange(property: KProperty<*>, oldValue: T, newValue: T) = onChange(property, oldValue, newValue)
}
getValue
和setValue
方法。上面的observable函数返回一个匿名对象ObservableProperty。我们看下它的源码实现* Implements the core logic of a property delegate for a read/write property that calls callback functions when changed.
* @param initialValue the initial value of the property.
*/
public abstract class ObservableProperty<T>(initialValue: T) : ReadWriteProperty<Any?, T> {
private var value = initialValue
/**
* The callback which is called before a change to the property value is attempted.
* The value of the property hasn't been changed yet, when this callback is invoked.
* If the callback returns `true` the value of the property is being set to the new value,
* and if the callback returns `false` the new value is discarded and the property remains its old value.
*/
protected open fun beforeChange(property: KProperty<*>, oldValue: T, newValue: T): Boolean = true
/**
* The callback which is called after the change of the property is made. The value of the property
* has already been changed when this callback is invoked.
*/
protected open fun afterChange(property: KProperty<*>, oldValue: T, newValue: T): Unit {}
public override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value
}
public override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
val oldValue = this.value
if (!beforeChange(property, oldValue, value)) {
return
}
this.value = value
afterChange(property, oldValue, value)
}
}
2020-11-19
2021-04-22
2021-01-14
2020-10-22