[AYJS] wpf设计模式学习[10]-观察者模式

讲解: 观察(Observer)与通知(Notify)

两个角色的设计模式.WPF最多的就是观察者模式比如,IPropertyNotifyChanged接口

ay肯定用WPF方式来演示这个思想。


新建一个控件父类(被Notify对象,Observer,Update对象),和一个 桌面平台技术父类(Notify角色)

  public interface Visual
    {
        string Name { get; set; }
        void Update();
    }
    public interface WindowApplication
    {
        void Attach(Visual observer);
        void Detach(Visual observer);
        void Notify();
    }

 写一个通知技术

 public class WPF : WindowApplication
    {
        List<Visual> visuals = new List<Visual>();
        public void Attach(Visual observer)
        {
            visuals.Add(observer);
        }
        public void Detach(Visual observer)
        {
            visuals.Remove(observer);
        }

        public void Notify()
        {
            foreach (Visual item in visuals)
            {
                item.Update();
            }
        }
    }

添加两个控件

public class Button : Visual

    {

        public Button(string name)

        {

            this.Name = name;

        }

        public string Name { get; set; }

        public void Update()

        {

            Console.WriteLine("Button类型:" + Name + "控件下的数据已经更新");

        }

    }

    public class ToggleButton : Visual

    {

        public ToggleButton(string name)

        {

            this.Name = name;

        }

        public string Name { get; set; }

        public void Update()

        {

            Console.WriteLine("ToggleButton类型:" + Name + "控件下的数据已经更新");

        }

    }

 界面使用:

            WPF wpf = new WPF();

            Button btn1 = new Button("btn1");

            wpf.Attach(btn1);

            Button btn2 = new Button("btn2");

            wpf.Attach(btn2);

            Button btn3 = new Button("btn3");

            wpf.Attach(btn3);

            ToggleButton btn4 = new ToggleButton("tbtn4");

            wpf.Attach(btn4);

            //界面发生更新后,通知被绑定的控件 ayjs.net

            wpf.Notify();

            Console.WriteLine();

            wpf.Detach(btn3);

            wpf.Notify();

 

Image 12.png

ay的这是第一种通知方式,下面说下第二种

当然这里推荐使用abstract类去写,关于在这个DEMO的WPF类,上方还可以再加一个父类,完成模板模式的思想,把 Attach和Detach方法提取出去,子类再继承WPF的子类。

好了,这里不多说了,先到这

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值