//单例模式
public class Single {//使用同步锁防止多个线程同时访问这个单例
private static Single single;
private static Object obj = new Object();
private Single() { }
public static Single shareSingle() {
if (single == null) {
lock (obj) {
if (single == null) {
single = new Single();
}
}
}
return single;
}
}
//观察者模式
class Class2
{
static void Main(string[] args)
{
Customer subject = new Customer();
Accountant accountant = new Accountant(subject);
Cashier cashier = new Cashier(subject);
Dilliveryman dilliveryman = new Dilliveryman(subject);
//subject.Update += accountant.GiveInvoice;
//subject.Update += cashier.Recoded;
//subject.Update += dilliveryman.Dilliver;
//subject.CustomerState = "已付款";
subject.Notify();
Console.Write(accountant.accountantState);
Console.Read();
}
}
public interface ISubject
{
void Notify();
}
public class Customer : ISubject
{
private string customerState;
public delegate void CustomerEventHandler();//声明委托
public event CustomerEventHandler Update;
public void Notify()
{
if (Update != null)
{
Console.WriteLine("我来买东西了");
Update();
}
}
public string CustomerState
{
get { return customerState; }
set { customerState = value; }
}
}
public class Accountant
{
public string accountantState;
public Accountant(Customer customer)
{
customer.Update += GiveInvoice;
}
public void GiveInvoice()
{
Console.WriteLine("我是会计,我来开具发票。");
accountantState = "已开发票";
}
}
public class Cashier
{
private string cashierState;
public Cashier(Customer customer)
{
customer.Update += Recoded;
}
public void Recoded()
{
Console.WriteLine("我是出纳员,我给登记入账。");
cashierState = "已入账";
}
}
public class Dilliveryman
{
private string dillivierymanState;
public Dilliveryman(Customer customer)
{
customer.Update += Dilliver;
}
public void Dilliver()
{
Console.WriteLine("我是配送员,我来发货");
dillivierymanState = "已发货";
}
}