public class 主程序 { [STAThread] public static void Main(string[] args) { 猫 爱叫的猫 = new 猫(); 猫.CatShout += new CatShoutHandler (老鼠跑,主人醒等等);
猫.猫叫() ... } }public class 猫 { public event CatShoutHandler CatShout; public 猫叫() { if(CatShout != null) { CatShout(this,new EventArgs()); }}} // 定义委托处理程序 public delegate void CatShoutHandler(object sender,System.EventArgs e);
老题目了两种方法 1 使用观察者模式 public interface Observer { void Response(); //观察者的响应,如是老鼠见到猫的反映 } public interface Subject { void AimAt(Observer obs); //针对哪些观察者,这里指猫的要扑捉的对象---老鼠 } public class Mouse : Observer { private string name; public Mouse(string name, Subject subj) { this.name = name; subj.AimAt(this); }
public void Response() { Console.WriteLine(name + " attempt to escape!"); } } public class Master : Observer { public Master(Subject subj) { subj.AimAt(this); }
public void Response() { Console.WriteLine("Host waken!"); } }
public class Cat : Subject { private ArrayList observers; public Cat() { this.observers = new ArrayList(); } public void AimAt(Observer obs) { this.observers.Add(obs); } public void Cry() { Console.WriteLine("Cat cryed!"); foreach (Observer obs in this.observers) { obs.Response(); } } } class MainClass { static void Main(string[] args) { Cat cat = new Cat(); Mouse mouse1 = new Mouse("mouse1", cat); Mouse mouse2 = new Mouse("mouse2", cat); Master master = new Master(cat); cat.Cry(); } }2 使用事件 public delegate void SubEventHandler(); public abstract class Subject { public event SubEventHandler SubEvent; protected void FireAway() { if (this.SubEvent != null) this.SubEvent(); } } public class Cat : Subject { public void Cry() { Console.WriteLine("cat cryed."); this.FireAway(); } } public abstract class Observer { public Observer(Subject sub) { sub.SubEvent += new SubEventHandler(Response); } public abstract void Response(); } public class Mouse : Observer { private string name; public Mouse(string name, Subject sub) : base(sub) { this.name = name; } public override void Response() { Console.WriteLine(name + " attempt to escape!"); } } public class Master : Observer { public Master(Subject sub) : base(sub){} public override void Response() { Console.WriteLine("host waken"); } } class Class1 { static void Main(string[] args) { Cat cat = new Cat(); Mouse mouse1 = new Mouse("mouse1", cat); Mouse mouse2 = new Mouse("mouse2", cat); Master master = new Master(cat); cat.Cry(); } }
Cat cat = new Cat(); Mouse mouse1 = new Mouse("mouse1", cat); Mouse mouse2 = new Mouse("mouse2", cat); Master master = new Master(cat);--------------- 这段不是很好,耦合太强,如果现在多一个Subject,比如:如果人和老鼠受猫嚎的影响,还受灯打开的影响,那得大改程序了。 能不能把事件通知独立出来。即事件通知服务器
Cat cat = new Cat(); Mouse mouse1 = new Mouse("mouse1", cat); Mouse mouse2 = new Mouse("mouse2", cat); Master master = new Master(cat);这样的耦合性太强了,如果主人还养了狗呢?主人还有闹钟呢? 是不是可以设计一个声音管理类 SoundMaster sm = SoundMaster(); //老鼠和人都向它订阅声音事件 Mouse mouse1 = new Mouse("mouse1"); sm.addlistener(mouse1); Master master = new Master(); sm.addlistener(master); //猫发起声音 Cat cat = new Cat(); cat.cry(sm);mouse和master继承listen接口. mouse.lister( soundtype st) { if st=猫叫||狗叫...... 跑; }master.lister( soundtype st) { if st=猫叫||狗叫......||闹钟 醒; if st=老婆呻吟 up,up,up!!! }
Java Edition/* * Created on 2005/09/14 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.rcom10002;/** * @author bunseki * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public interface IAction {
public String getName();
public void Action();
}/* * Created on 2005/09/14 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.rcom10002;/** * @author bunseki * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public interface IReg {
public void Add(IAction iAction);
public void Remove(IAction iAction);
}/* * Created on 2005/09/15 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.rcom10002;/** * @author bunseki * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ abstract class Actors implements IAction { protected String name; public Actors(String value) { this.name = value; }
public String getName(){ return this.name; } }
/* * Created on 2005/09/14 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.rcom10002;import java.util.HashMap; import java.util.Iterator;/** * @author bunseki * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class Cats extends Actors implements IReg{
private HashMap<String, IAction> members;
public Cats(String value){ super(value); this.members = new HashMap<String, IAction>(); }
public void Action(){ this.Meow(); Iterator member = this.members.keySet().iterator(); while (member.hasNext()){ String key = (String)member.next(); IAction iAction = (IAction)members.get(key); iAction.Action(); } }
public void Add(IAction iAction){ if (!this.members.containsKey(iAction.getName())){ this.members.put(iAction.getName(), iAction); } }
public void Remove(IAction iAction){ this.members.remove(iAction.getName()); } }/* * Created on 2005/09/14 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.rcom10002;import java.util.HashMap; import java.util.Iterator;/** * @author bunseki * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class Rats extends Actors implements IReg{
private HashMap<String, IAction> members;
public Rats(String value){ super(value); this.members = new HashMap<String, IAction>(); }
public void Action(){ this.Squeak(); Iterator member = this.members.keySet().iterator(); while (member.hasNext()){ String key = (String)member.next(); IAction iAction = (IAction)members.get(key); iAction.Action(); } }
public void Add(IAction iAction){ if (!this.members.containsKey(iAction.getName())){ this.members.put(iAction.getName(), iAction); } }
public void Remove(IAction iAction){ this.members.remove(iAction.getName()); } }/* * Created on 2005/09/14 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.rcom10002;/** * @author bunseki * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class Owners extends Actors{
/* * Created on 2005/09/14 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.rcom10002;/** * @author bunseki * * TODO To change the template for this generated type comment go to Window - * Preferences - Java - Code Style - Code Templates */public class TestEnvironment { public static void main(String[] args) { Cats cat = new Cats("Tom"); Rats rat = new Rats("Jerry"); Owners owner = new Owners("Jessica"); cat.Add(rat); rat.Add(owner); cat.Action(); }
2。考虑可扩展性,战士的叫声可能引起其他联动效应
{
[STAThread]
public static void Main(string[] args)
{
猫 爱叫的猫 = new 猫(); 猫.CatShout += new CatShoutHandler (老鼠跑,主人醒等等);
猫.猫叫()
...
}
}public class 猫
{
public event CatShoutHandler CatShout;
public 猫叫()
{
if(CatShout != null)
{
CatShout(this,new EventArgs());
}}} // 定义委托处理程序
public delegate void CatShoutHandler(object sender,System.EventArgs e);
1 使用观察者模式
public interface Observer
{
void Response(); //观察者的响应,如是老鼠见到猫的反映
}
public interface Subject
{
void AimAt(Observer obs); //针对哪些观察者,这里指猫的要扑捉的对象---老鼠
}
public class Mouse : Observer
{
private string name;
public Mouse(string name, Subject subj)
{
this.name = name;
subj.AimAt(this);
}
public void Response()
{
Console.WriteLine(name + " attempt to escape!");
}
}
public class Master : Observer
{
public Master(Subject subj)
{
subj.AimAt(this);
}
public void Response()
{
Console.WriteLine("Host waken!");
}
}
public class Cat : Subject
{
private ArrayList observers;
public Cat()
{
this.observers = new ArrayList();
}
public void AimAt(Observer obs)
{
this.observers.Add(obs);
}
public void Cry()
{
Console.WriteLine("Cat cryed!");
foreach (Observer obs in this.observers)
{
obs.Response();
}
}
}
class MainClass
{
static void Main(string[] args)
{
Cat cat = new Cat();
Mouse mouse1 = new Mouse("mouse1", cat);
Mouse mouse2 = new Mouse("mouse2", cat);
Master master = new Master(cat);
cat.Cry();
}
}2 使用事件
public delegate void SubEventHandler();
public abstract class Subject
{
public event SubEventHandler SubEvent;
protected void FireAway()
{
if (this.SubEvent != null)
this.SubEvent();
}
}
public class Cat : Subject
{
public void Cry()
{
Console.WriteLine("cat cryed.");
this.FireAway();
}
}
public abstract class Observer
{
public Observer(Subject sub)
{
sub.SubEvent += new SubEventHandler(Response);
}
public abstract void Response();
}
public class Mouse : Observer
{
private string name;
public Mouse(string name, Subject sub) : base(sub)
{
this.name = name;
}
public override void Response()
{
Console.WriteLine(name + " attempt to escape!");
}
}
public class Master : Observer
{
public Master(Subject sub) : base(sub){}
public override void Response()
{
Console.WriteLine("host waken");
}
}
class Class1
{
static void Main(string[] args)
{
Cat cat = new Cat();
Mouse mouse1 = new Mouse("mouse1", cat);
Mouse mouse2 = new Mouse("mouse2", cat);
Master master = new Master(cat);
cat.Cry();
}
}
Mouse mouse1 = new Mouse("mouse1", cat);
Mouse mouse2 = new Mouse("mouse2", cat);
Master master = new Master(cat);---------------
这段不是很好,耦合太强,如果现在多一个Subject,比如:如果人和老鼠受猫嚎的影响,还受灯打开的影响,那得大改程序了。
能不能把事件通知独立出来。即事件通知服务器
Mouse mouse1 = new Mouse("mouse1", cat);
Mouse mouse2 = new Mouse("mouse2", cat);
Master master = new Master(cat);这样的耦合性太强了,如果主人还养了狗呢?主人还有闹钟呢?
是不是可以设计一个声音管理类
SoundMaster sm = SoundMaster();
//老鼠和人都向它订阅声音事件
Mouse mouse1 = new Mouse("mouse1");
sm.addlistener(mouse1);
Master master = new Master();
sm.addlistener(master);
//猫发起声音
Cat cat = new Cat();
cat.cry(sm);mouse和master继承listen接口.
mouse.lister( soundtype st)
{
if st=猫叫||狗叫......
跑;
}master.lister( soundtype st)
{
if st=猫叫||狗叫......||闹钟
醒;
if st=老婆呻吟
up,up,up!!!
}
* Created on 2005/09/14
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.rcom10002;/**
* @author bunseki
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public interface IAction {
public String getName();
public void Action();
}/*
* Created on 2005/09/14
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.rcom10002;/**
* @author bunseki
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public interface IReg {
public void Add(IAction iAction);
public void Remove(IAction iAction);
}/*
* Created on 2005/09/15
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.rcom10002;/**
* @author bunseki
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
abstract class Actors implements IAction { protected String name; public Actors(String value) {
this.name = value;
}
public String getName(){
return this.name;
}
}
* Created on 2005/09/14
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.rcom10002;import java.util.HashMap;
import java.util.Iterator;/**
* @author bunseki
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class Cats extends Actors implements IReg{
private HashMap<String, IAction> members;
public Cats(String value){
super(value);
this.members = new HashMap<String, IAction>();
}
private void Meow(){
System.out.println(this.name + ": meow~meow~~~");
}
public void Action(){
this.Meow();
Iterator member = this.members.keySet().iterator();
while (member.hasNext()){
String key = (String)member.next();
IAction iAction = (IAction)members.get(key);
iAction.Action();
}
}
public void Add(IAction iAction){
if (!this.members.containsKey(iAction.getName())){
this.members.put(iAction.getName(), iAction);
}
}
public void Remove(IAction iAction){
this.members.remove(iAction.getName());
}
}/*
* Created on 2005/09/14
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.rcom10002;import java.util.HashMap;
import java.util.Iterator;/**
* @author bunseki
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class Rats extends Actors implements IReg{
private HashMap<String, IAction> members;
public Rats(String value){
super(value);
this.members = new HashMap<String, IAction>();
}
private void Squeak(){
System.out.println(this.name + ": squeak~squeak~~~");
}
public void Action(){
this.Squeak();
Iterator member = this.members.keySet().iterator();
while (member.hasNext()){
String key = (String)member.next();
IAction iAction = (IAction)members.get(key);
iAction.Action();
}
}
public void Add(IAction iAction){
if (!this.members.containsKey(iAction.getName())){
this.members.put(iAction.getName(), iAction);
}
}
public void Remove(IAction iAction){
this.members.remove(iAction.getName());
}
}/*
* Created on 2005/09/14
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.rcom10002;/**
* @author bunseki
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class Owners extends Actors{
public Owners(String value){
super(value);
}
private void Ah(){
System.out.println(this.name + ": Ah~~");
}
public void Action(){
this.Ah();
}
}
* Created on 2005/09/14
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.rcom10002;/**
* @author bunseki
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/public class TestEnvironment { public static void main(String[] args) { Cats cat = new Cats("Tom");
Rats rat = new Rats("Jerry");
Owners owner = new Owners("Jessica");
cat.Add(rat);
rat.Add(owner);
cat.Action();
}
}
charles_y(难得糊涂) 的解答是很完整的,
如果是C#程序员,用事件是最简单的办法,
如果是C++程序员用观察者模式比较好,
这是一个很精典的设计模式。
http://blog.csdn.net/johnsuna/archive/2004/12/31/235729.aspx
-----------------------
厉害,很细致.....
{
public:
some_one_shout( int who ){ broadcast_all_in_register_map();}
register_hear_func( int who, func f ){register_map[who] = f;}
private:
std::map<int,func> register_map;
}
system sys;class cat:public object
{
public:
void shout(){sys.some_one_shout(const_CAT);}
}
class mouse:public object
{
public:
mouse(){sys.register_hear_func( const_MOUSE, this->hear );}
void hear(int who)
{
if( const_CAT == who )
this->run_away()
}
}
class human:public object
{
public:
human(){sys.register_hear_func( const_HUMAN, this->hear );}
void hear( int who )
{
if( sleeping && const_CAT == who )
this->wake_up()
}
}小试一把C++版本的
呵呵,出题的人水平有限。不过还好,做题的人思路也有限,所以正好。
要是我,第一会问,猫、主人、耗资在不在一个进程里,进而在不在一台计算机里……还有,它们的数量有多少(会不会有大并发问题)
=================
这位兄弟,你是不是还要再加上:
猫、鼠、主人,如果都不是在计算机里
正常点是吧,这里是面试。
using System.Collections;namespace ConsoleApplication1
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
Mouse mouse1=new Mouse("mouse1");
Mouse mouse2=new Mouse("mouse2");
Mouse mouse3=new Mouse("mouse3"); Cat cat=new Cat("cat1");
cat.AddEvent(mouse1);
cat.AddEvent(mouse2);
cat.AddEvent(mouse3); Human human=new Human("John"); cat.AddEvent(human); cat.Shout();
Console.Read();
} }
public interface IShout
{
void doSomething(Cat cat);
} public class Cat
{
public Cat(string name)
{
m_Name=name;
}
ArrayList eventList=new ArrayList();
private string m_Name; public void AddEvent(IShout shout)
{
eventList.Add(shout);
}
public void Shout()
{
Console.WriteLine("Cat "+m_Name+" shout");
foreach(IShout shout in eventList)
{
shout.doSomething(this);
}
}
}
public class Mouse:IShout
{
string m_Name; public Mouse (string mouseName)
{
m_Name=mouseName;
}
#region IShout 成员 public void doSomething(Cat cat)
{
Console.WriteLine(m_Name+" 到处跑 " );
} #endregion
} public class Human:IShout
{
string m_Name; public Human (string mouseName)
{
m_Name=mouseName;
}
#region IShout 成员 public void doSomething(Cat cat)
{
Console.WriteLine(m_Name+" 惊醒 ");
} #endregion }}
-----------------
也在学习ing,这个无委托版
CSDN小助手是一款脱离浏览器也可以访问Csdn论坛的软件
速度快;使用方便;提供源代码。
界面:http://blog.csdn.net/Qqwwee_Com/category/146601.aspx
下载:http://szlawbook.com/csdnv2
using System.Collections;
namespace SceneA
{
public delegate void SceneEventHandler(object sender, CharEventArgs e); public class CharEventArgs : EventArgs
{
public string Action;
public CharEventArgs(string Action)
{
this.Action = Action;
}
}public class Animal
{
protected Hashtable EventList= new Hashtable();
protected Scene CurrentScene;
protected string Name;
public Animal(string Name,Scene SceneObj)
{
this.Name=Name;
this.CurrentScene=SceneObj;
SceneObj.AddListener(this);
}
public void AddEventListener(string e,SceneEventHandler Action)
{
EventList.Add(e,Action);
}
public void Trigger(string Action)
{
CurrentScene.PostMessage(this,Action);
}
public void Dispatch(Object Obj,CharEventArgs e)
{
Object fun;
if(EventList.Count==0)
{
// Console.WriteLine(this.Name+"说:没我啥事 你们继续");
}else if(null!=(fun=EventList[e.Action]))
((SceneEventHandler)fun)(Obj,e);
}
}
public class Cat:Animal
{
public Cat(string Name,Scene SceneObj):base(Name,SceneObj){}
}
public class Dog:Animal
{
public Dog(string Name,Scene SceneObj):base(Name,SceneObj){}
}
public class Mouse:Animal
{
public Mouse(string Name,Scene SceneObj):base(Name,SceneObj){
AddEventListener("喵",new SceneEventHandler(Escape));
}
public void Escape(object sender, CharEventArgs e)
{
if(sender.ToString()=="SceneA.Dog")
{
Console.WriteLine(sender.ToString()+e.Action+"→"+ this.Name+"说:这家伙是狗甭理它!");
return;
}
Console.WriteLine(sender.GetType().ToString()+e.Action+"→"+ this.Name+"说:快快逃呀");
}
}
public class Man:Animal
{
public Man(string Name,Scene SceneObj):base(Name,SceneObj){}
}
public class Scene
{
private event SceneEventHandler SceneEvent; public void PostMessage(Animal Animal,string Action)
{
this.SceneEvent(Animal,new CharEventArgs(Action));
}
public void AddListener(Animal Animal)
{
this.SceneEvent += new SceneEventHandler(Animal.Dispatch);
}
public void ManWake(object sender, CharEventArgs e)
{
Console.WriteLine(sender.ToString()+e.Action+"→吵死啦!");
} [STAThread]
static void Main(string[] args)
{
Scene MainScene = new Scene(); Cat CatObj = new Cat("汤姆",MainScene);
Mouse MouseJL = new Mouse("杰里",MainScene);
Mouse MouseJM = new Mouse("杰妹",MainScene);
Dog DogObj = new Dog("旺财",MainScene); Man ManObj = new Man("小强",MainScene);
ManObj.AddEventListener("喵",new SceneEventHandler(MainScene.ManWake)); CatObj.Trigger("喵");
DogObj.Trigger("喵"); }
}
}场景中可以任意添加角色,并各自定义要响应的事件,扩展性怎样?
能不能再来个多线程?
帖出代码让我们再观摩下
-----------------
厉害!好!
public class 猫叫EventArgs : EventArgs
{
private 叫声 猫叫声;
void 猫叫EventArgs(叫声 声音)
{
this.猫叫声 = 声音;
}
}
public class 猫
{
public event 猫叫EventHandler 猫叫; public 叫()
{
if(猫叫 != null)
{
猫叫(this,new EventArgs(白猫的叫声));
}
}}
public class 场景
{
[STAThread]
public static void Main(string[] args)
{
猫 白猫 = new 猫(); 白猫.猫叫 = new 猫叫EventHandler (老鼠跑) + new 猫叫EventHandler (主任醒);
白猫.叫();
}
}
public void 叫()