外观模式(设计模式学习笔记)

简介

  • 也叫“过程模式:外观模式为子系统中的一组接口提供一个一致的界面,此模式定义了 一个高层接口,这个接口使得这一子系统更加容易使用
  • 外观模式通过定义一个一致的接口,用以屏蔽内部子系统的细节,使得调用端只需跟这个接口发生调用,而无 需关心这个子系统的内部细节
  • 例题:
    学生管理系统:要求编写指定学生动作的程序
    传统解决方案:
    在这里插入图片描述

问题分析

  1. 创建各个子系统的对象,并直接去调用子系统(对象)相关方法,会造成调用过程混乱
  2. 不利于系统的维护以及对子系统的操作
  3. 解决思路:定义一个管理接口,管理子系统
  4. 类图:
    在这里插入图片描述
public class Manage {
    
    
	private Act1 a1;
	private Act2 a2;
	private Act3 a3;

	public Manage() {
    
    

		this.a1 = Act1.getInstant();
		this.a2 = Act2.getInstant();
		this.a3 = Act3.getInstant();
		Meet();
		Talk();
		Bye();
	}

	public void Meet() {
    
    
		a1.Method1(a2.getName());
		a2.Method1(a1.getName());
		a1.Method1(a3.getName());

	}

	public void Talk() {
    
    
		a1.Method2();
		a3.Method2();
	}

	public void Bye() {
    
    
		a1.Method3();
		a2.Method3();
		a3.Method3();
	}

}

public class Act1 {
    
    
	private static Act1 act = new Act1();

	String name = "tom";
	public String getName() {
    
    
		return name;
	}

	public static Act1 getInstant() {
    
    
		return act;
	}

	public void Method1(String name) {
    
    
		System.out.println("Hello " + name);
	}

	public void Method2() {
    
    
		System.out.println("Nice to meet you");
	}

	public void Method3() {
    
    
		System.out.println("me too");

	}
}

public class Act2 {
    
    
	private static Act2 act = new Act2();
	String name = "tim";

	public static Act2 getInstant() {
    
    
		return act;
	}

	public String getName() {
    
    
		return name;
	}

	public void Method1(String name) {
    
    
		System.out.println("Hello " + name);
	}

	public void Method2() {
    
    
		System.out.println("Nice to meet you");
	}

	public void Method3() {
    
    
		System.out.println("me too");

	}
}

public class Act3 {
    
    
	private static Act3 act = new Act3();
	String name = "siri";

	public String getName() {
    
    
		return name;
	}

	public static Act3 getInstant() {
    
    
		return act;
	}

	public void Method1(String name) {
    
    
		System.out.println("Hello " + name);
	}

	public void Method2() {
    
    
		System.out.println("Nice to meet you");
	}

	public void Method3() {
    
    
		System.out.println("me too");

	}
}

public class Client {
    
    
	public static void main(String[] args) {
    
    
		new Manage();
		
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_44763595/article/details/107876577