码迷,mamicode.com
首页 > 其他好文 > 详细

Design Pattern

时间:2015-01-10 17:58:32      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

1.策略模式

技术分享
using System;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            A a = new B();
            a.Say();
            a.SetAction(new ActionB());
            a.Say();
            a = new C();
            a.Say();
            Console.Read();

        }
    }

    public interface TheAction
    {
        void Say();
    }
    public abstract class A
    {
        public TheAction theAction;
        public void Say()
        {
            theAction.Say();
        }
        public void SetAction(TheAction a)
        {
            theAction = a;
        }
    }
    public class B : A
    {
        public B()
        {
            theAction = new ActionA();
        }
    }
    public class C : A
    {
        public C()
        {
            theAction = new ActionB();
        }
    }
    public class ActionA : TheAction
    {
        public void Say()
        {
            Console.WriteLine("Action A");
        }
    }
    public class ActionB : TheAction
    {
        public void Say()
        {
            Console.WriteLine("Action B");
        }
    }
}
策略模式

 

2.观察者模式

技术分享
using System;
using System.Collections.Generic;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Observer o = new Observer();
            Subject s = new Subject(o);
            o.SetA("Hello World");
            o.SetA("Have a good day");
            Console.Read();
        }
    }

    public class Observer
    {
        public List<Subject> subjects;
        public Observer()
        {
            subjects = new List<Subject>();
        }
        public string A { get; set; }
        public void Regist(Subject subject)
        {
            subjects.Add(subject);
        }
        public void UnRegist(Subject subject)
        {
            subjects.Remove(subject);
        }
        public void notifyObservers()
        {
            foreach (var item in subjects)
            {
                item.Update(A);
            }
        }
        public void SetA(string a)
        {
            A = a;
            notifyObservers();
        }
    }
    public class Subject
    {
        public Observer observer;
        public Subject(Observer o)
        {
            observer = o;
            observer.Regist(this);
        }
        public string A { get; set; }
        public void Update(string a) { A = a;Display(); }
        public void Display()
        {
            Console.WriteLine(A);
        }
    }
    
}
观察者模式

 

Design Pattern

标签:

原文地址:http://www.cnblogs.com/CodingArt/p/4215167.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!