Swift Observer mode

Source: Internet
Author: User

Using Swift to write an observer pattern, a collection of swift language classes, arrays, protocols, methods, strings, conditional control statements and some other syntax.
A brief introduction to the observer pattern, in the observer pattern, would change the state of the subject and the number of observers. With this pattern, you can change the objects that depend on the subject state, without having to change the theme.

//main.swift//Observer(观察者模式)//Created by jy on 15/4/26.//Copyright (c) 2015年 jy. All rights reserved. import Foundation//观察者模式中,会改变的是主题的状态以及观察者的数目。用这个模式,可以改变依赖于主题状态的对象,去不必改变主题。//主题和观察者都使用协议:观察者利用主题的协议向主题注册,而主题利用观察者协议(接口)通知观察者。这样可以让两者运作正常,又同时具有松耦合的特点//定义协议,观察者要实现的protocol Observerable{    func update();}//观察者实现协议class Subscriber : Observerable{    //定义属性状态    func update() {        println("Callback")    }}/*** 主题*/class Paper{    //定义空数组    var observers = Array<Subscriber>()    //注册观察者    func register(sub:Subscriber){        self.observers.append(sub)    }    //外部统一访问    func trigger(){        var count = self.observers.count;        //判断是否注册为空        if count != 0 {            for obs in self.observers {                //通知                obs.update()            }        }    }}var paper = Paper()//观察者var sub1 = Subscriber()var sub2 = Subscriber()//注册paper.register(sub1)paper.register(sub2)paper.trigger()

Swift Observer mode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.