Chapter One
public class MallarDuck extends Duck
{
public MallardDuck()
{
flyBhavior = new FlyWithWings();
}
}
public abstract class Duck
{
// 为行为接口类型声明引用变量
FlyBehavior flyBehavior;
public Duck() {}
public abstract void display();
public void performFly()
{
//委托给行为类
flyBehavior.fly();
}
}
// 飞行行为类的借口必须实现的接口
public interface FlyBehavior
{
public void fly();
}
// 飞行类 1
public class FlyWithWings implements FlyBehavior
{
public void fly()
{
System.out.println("I'm flying");
}
}
// 飞行类 2
public class FlyNoWay implements FlyBehavior
{
public void fly()
{
System.out.println("I can't fly");
}
}
个人总结:先抽出飞行类。
抽象类 Duck 中 performFly() 。
而由子类 MallarDuck 指定的用哪种方式去飞行。
飞行类 FlyWithWings 来实现具体细节。
解决了原来在抽象类 Duck 添加 fly()方法时,每个子类都要实现 fly()方法,代码无法重用的情况。
/*******笔记 (不是本人翻译,网上已有译本第1章) 本人英语差,看一章用了4天**************/
http://webseminar.unix105.cn4e.com/book/hfdp_chapter1.pdf
The best way to use patterns is to load your brain with them and then recognize places in your designs and existing applications where you can apply them.
使用模式最好的方式是:[把模式装进脑子中,然后在你的设计和已有的应用中,寻找何处可以运用它们]
How hard can it be?
这有什么困难?
what he thought was a great use of inheritance for the purpose of reuse hasn't turned out so well when it comes to maintenance.
他体会到当涉及维护时为了复用的目地而使用继承,结局并不完美。
Wouldn't it be dreamy if only there were a way to build software so that when we need to change it , we could do so with the least possible impact on the existing code?We could spend less time reworking code and more making the program do cooler things...
如果能有一种建立软件的方法,好让我们需要改变软件时,可以在对即有的代码影响最小的情况下,轻易达到花较少时间重做代码,而多让程序去做更酷的事。
该有多好...
Take what varies and "encapsulate" it so it won't affect the rest of your code.
把变化"封装"起来,好让其它部分不会受到影响。
take the parts that vary and encapsulate them, so that later you can alter or extend the parts that vary without affecting those that don't.
把会变化的部份取出并封装起来,以便以后可以轻易地扩充此部份,而不影响不需要变化的其它部份。
/*************Design Principle**************************************/
Identify the aspects of your application that vary and separate them from what stays the same.
找出应该中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起。
Program to an interface,not an implementation.
针对接口编程,而不是针对实现编程。
Favor composition over inheriance.
多用组合,少用继承
/*************Design Patterns**************************************/
The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
策略模式 定义了算法族,分别封装起来,让它们之间可以互相替换,些模式让算法的变化独立于使用算法的客户。
本文介绍如何使用策略模式解决代码重复及扩展性问题。通过将不同飞行行为封装为接口及其实现,实现在Duck抽象类及其子类间的灵活切换。
939

被折叠的 条评论
为什么被折叠?



