Home > Java > javaTutorial > Classic case of java facade pattern

Classic case of java facade pattern

黄舟
Release: 2017-03-10 13:22:36
Original
1685 people have browsed it

Class diagram:



##

/**
 * 角色
 * @author stone
 *
 */
public class Actor {
	public Actor(String name) {
		System.out.println("创建了角色: " + name);
	}
	
	public void load() {
		System.out.println("角色加载");
	}
	
	public void unload() {
		System.out.println("角色退出,存档");
	}
}
Copy after login
/**
 * 场景
 * @author stone
 *
 */
public class Scene {
	public Scene(String name) {
		System.out.println("创建了场景: " + name);
	}
	
	public void load() {
		System.out.println("场景加载");
	}
	
	public void unload() {
		System.out.println("场景卸载");
	}
}
Copy after login


/**
 * 外观类,即一个业务功能类,它的实现需要持有其他具体的 业务对象
 * @author stone
 *
 */
public class Facade {
	Actor actor;
	Scene scene;
	
	public Facade() {
		this.actor = new Actor("lisi");
		this.scene = new Scene("海天盛宴");
	}
	
	public void startGame() {
		actor.load();
		scene.load();
	}
	
	public void endGame() {
		actor.unload();
		scene.unload();
	}
}
Copy after login


/**
 * 外观(Facade)模式
 * 		简单的说就是降低了类与类之间的耦合度,使用一个Facade类来持有原有类的引用。它使用的频率其实非常的高
 * 跟静态代理在实现上有些类似,不同的是,外观模式中可以持有多个实体对象的引用,进行组合实现业务功能
 * @author stone
 *
 */
public class Test {
	public static void main(String[] args) {
		/*
		 * 如果不使用外观模式,那么在Actor和Scene可能至少一方需要持有对方的引用
		 * 当需要添加新的具体功能类时,只需要在Facade中添加一个引用,在相应的周期函数中使用即可
		 */
		Facade facade = new Facade();
		facade.startGame();
		System.out.println("----");
		facade.endGame();
	}
}
Copy after login

Print:

创建了角色: lisi
创建了场景: 海天盛宴
角色加载
场景加载
----
角色退出,存档
场景卸载
Copy after login

The above is the detailed content of Classic case of java facade pattern. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template