《Head First 设计模式》学习笔记——适配器模式 + 外观模式

在ADO.NET中,对于我们从数据库中取出的数据都要放到一个DataSet中,无论你是Access的数据库,还是SQL的数据库,或者是Oracle的数据库都要放到DataSet中。.NET中并没有提供如:SqlDataSet、OleDbDataSet、OracleDataSet等,它仅仅提供了一种DataSet就是用SqlDataAdapte等去填充数据;为什么这一个DataSet能存放不同的数据呢?就是有这些适配器来适配。————题记

设计模式
适配器模式:将一个类的接口。转换成客户期待的还有一个接口。适配器让原来接口不兼容的类能够合作无间。
包括两种适配器:对象适配器和类适配器。

区别在于前者使用组合。后者使用继承方法。


外观模式:提供统一的接口,用来訪问子系统中的一群接口。外观定义了一个高层接口,让子系统变得easy使用。

设计原则
“最少知识原则”:仅仅和你的密友谈话。

指导方针:就不论什么对象而言,在该对象的方法内,我们仅仅应该调用属于下面范围的方法:
(1)该对象本身
(2)被当做方法的參数而传递进来额对象
(3)此方法所创建或实例化的不论什么对象
(4)对象的不论什么组件

要点
当须要使用一个现有的类而其接口并不符合你的须要时,就使用适配器。
当须要简化。并使用一个非常大的接口或者一群负责的接口时。就使用外观模式。
适配器改变接口以符合客户的期望,外观将客户从一个复杂的子系统中解耦。

适配器模式有两种模式:对象适配器和类适配器,类适配器须要用到多重继承。

适配器将一个对象包装起来以改变其接口。装饰者将一个对象包装起来以添加新的行为和责任。而外观将一群对象包装起来以简化其接口。


public interface Duck {
	public void quack();

	public void fly();
}

//implements实现接口
public class MallardDuck implements Duck {
	public void quack() {
		System.out.println("Quack");
	}

	public void fly() {
		System.out.println("I'm flying");
	}
}


public interface Turkey {
	public void gobble();

	public void fly();
}

//implements实现接口
public class WildTurkey implements Turkey {
	public void gobble() {
		System.out.println("Gobble gobble");
	}

	public void fly() {
		System.out.println("I'm flying a short distance");
	}
}

//首先,须要实现想转换成的类型接口
public class TurkeyAdapter implements Duck {
	Turkey turkey;

	//接着。须要获得要适配对象的引用
	public TurkeyAdapter(Turkey turkey) {
		this.turkey = turkey;
	}

	//须要实现接口中的全部方法
	public void quack() {
		turkey.gobble();
	}

	public void fly() {
		for (int i = 0; i < 5; i++) {
			turkey.fly();
		}
	}
}

public class DuckTestDrive {
	public static void main(String[] args) {
		MallardDuck duck = new MallardDuck();

		WildTurkey turkey = new WildTurkey();
		//将火鸡包装进一个火鸡适配器
		Duck turkeyAdapter = new TurkeyAdapter(turkey);

		System.out.println("The Turkey says...");
		turkey.gobble();
		turkey.fly();

		System.out.println("
The Duck says...");
		testDuck(duck);

		System.out.println("
The TurkeyAdapter says...");
		testDuck(turkeyAdapter);
	}

	static void testDuck(Duck duck) {
		duck.quack();
		duck.fly();
	}
}


【推广】 免费学中医,健康全家人
原文地址:https://www.cnblogs.com/ldxsuanfa/p/10523381.html