小事例让你快速理解java观察者模式

package cn.lfd.observer;

//被观察者
public class Person {
	private PersonListener personListener;
	
	public void eat() {//被观察者行为
		System.out.println("我在吃");
		if(personListener!=null) {
			personListener.doeat(new Event(this));//被观察者发生行为时,观察者会做出响应
		}
	}
	
	public void sleep() {
		System.out.println("我在睡觉");
		if(personListener!=null) {
			personListener.dosleep(new Event(this));
		}
	}
	
	public void addListenner(PersonListener personListener) {//提供一个方法接收一个观察者的观察
		this.personListener = personListener;
	}
}

//成为观察者需要实现的接口
interface PersonListener {
	public void doeat(Event e);
	
	public void dosleep(Event e);
}

//发生的事件,通过事件可以得到被观察者
class Event {
	private Person sourse;
	
	public Event(Person sourse) {
		super();
		this.sourse = sourse;
	}

	public Person getSourse() {
		return sourse;
	}

	public void setSourse(Person sourse) {
		this.sourse = sourse;
	}
}

测试代码:

package cn.lfd.observer;

public class TestPerson {
	public static void main(String[] args) {
		Person p = new Person();//创建一个被观察者
		p.addListenner(new PersonListener() {//为被观察者添加一个观察者
			
			public void dosleep(Event e) {//观察者对被观察者的行为应该作出什么反应
				System.out.println("吃死你");
			}
			
			public void doeat(Event e) {
				System.out.println("睡死你");
			}
		});
		
		p.eat();//被观察者发生行为
		p.sleep();
	}
}

小提示:

java设计模式来源于生活,感到困惑时,不妨想一想生活中的事例,或许你会体会到柳暗花明又一村的喜悦。

抽象工厂模式是一种创建型设计模式,它提供了一种创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。这种模式属于创建型模式,它提供了一种创建对象的最佳方式。 下面是一个简单的 Java 抽象工厂模式的示例: 假设我们正在开发一个游戏,游戏中有两个阵营:人类和兽人。每个阵营都有自己的建筑、士兵和武器。我们可以使用抽象工厂模式来创建这些对象。 首先,我们需要定义一个抽象工厂接口,该接口定义了创建建筑、士兵和武器的方法: ``` public interface GameFactory { Building createBuilding(); Soldier createSoldier(); Weapon createWeapon(); } ``` 然后,我们需要为每个阵营实现一个具体的工厂类,这些类将实现 GameFactory 接口并创建与其阵营相关的对象: ``` public class HumanFactory implements GameFactory { public Building createBuilding() { return new HumanBuilding(); } public Soldier createSoldier() { return new HumanSoldier(); } public Weapon createWeapon() { return new HumanWeapon(); } } public class OrcFactory implements GameFactory { public Building createBuilding() { return new OrcBuilding(); } public Soldier createSoldier() { return new OrcSoldier(); } public Weapon createWeapon() { return new OrcWeapon(); } } ``` 最后,我们可以使用这些工厂类来创建游戏对象: ``` GameFactory factory = new HumanFactory(); Building building = factory.createBuilding(); Soldier soldier = factory.createSoldier(); Weapon weapon = factory.createWeapon(); ``` 这样,我们就可以轻松地创建与特定阵营相关的对象,而无需知道它们的具体实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值