我写的设计模式的文章总结

更新时间:2024-06-24 10:25:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

设计模式

设计模式的理解

研读GOF的\设计模式\和阎宏博士的\与模式\已经有一段时间,自己颇有一些体会,自己面向对象和软件设计模式有了一些深入的理解,下面就一步一步开始自己的模式历程吧,从最简单的工厂模式到适配器模式,从 State模式到Decorator模式,一直到最复杂难懂的visitor模式,没有一个模式不体现了前辈的聪明才智,需要我们大家用心去体会和理解

恰当地使用设计模式,能使软件系统的架构更合理,能使将来的维护和修改更方便,能使数据库表结构的设计更合理,恰当的冗余和数据关联,能使我们的软件更多地适应变化,总之,它的的作用是不可低估的!

1,简单工厂,工厂方法和抽象工厂模式

对于简单工厂来说,它的工厂只能是这个样子的 public class SimplyFactory { /**

* 静态工厂方法 */

public static Prouct factory(String which) throw NoSuchProductExcption {

if(which.equalIgnoreCase(\ {

return new Product1(); }

else if(which.equalsIgnoreCase(\ {

return new Product2(); }

else if(which.equalsIgnoreCase(\ {

return new Product3(); }

else throw NoSuchProductExcption(\ } } }

而对产品Product1,Product2,Product3,可以执行接口Product,也可以不执行接口Product(当然这样不好),这个Product接口只是用来抽象具体product用的

public interface Product {

1

设计模式

void productMethod1(); //这些只是 void productMethod2(); void productMethod3(); }

对工厂来说,只要有这么一种产品,一般来说就要在工厂里有它的生产的方法, 否则抛出异常,而要工厂生产的话,也必须下达生产什么产品的命令,至少要向工厂发出信号,让工厂足以区分是要生产什么产品,否则工厂是不知道生产哪一种产品,

对于简单工厂来说,就是需要在工厂中枚举所有的产品,所以说简单工厂还是非常笨的。

if(which.equalIgnoreCase(\ 只是用来区分生产什么产品的标记值,(也可以根据产品其它属性来判断,比如产品类型,产品大小,总之能够区分是什么产品的属性,或者是与产品属性相关的变量) 或者说标记值是A,生产A产品,或者工厂里定义不是这样的,我偏偏要生产B产品,或者再特殊一些,我偏偏要生产A产品+B产品,那么就要return new ProductA()+new ProductB()了。

这样,我们就可以看出一个问题来,如果要能够被简单工厂生产出来,就必须在简单工厂中有能够生产出的它的方法定义,当然还需要有这个具体产品类的定义,就是有class对应,这样确保在简单工厂中new 它的时候不会抛出 NoSuchProduct的Exception.

对于工厂方法来说

实质上它是让工厂实现了抽象的工厂接口,它把具体怎么生产一种东西,放在具体的工厂去实现了,所谓”延迟到子类中实现“ public interface Creator {

public Prouct factory(); }

public SubCreator1 implent Creator {

public Prouct factory() {

return new ConcreteProduct1(); } }

public SubCreator2 implent Creator {

public Prouct factory()

2

设计模式

{

return new ConcreteProduct2(); } }

请注意:返回类型是Product型的!!

这样客户端调用是直接new 一个具体工厂的实例,然后命令它去生产,而对于具体工厂的父类(既工厂接口,接口完全可以改成子类继承父类来实现,只是这样不好,不符合OO的原则),它完全不知道什么产品被生产了,甚至它连那个具体工厂被实例化它都不知道

抽象工厂模式

抽象工厂模式主要是用来解决具体产品是有几类产品簇的问题

public interface Creator {

public ProuctA factoryA(); public ProuctB factoryB(); }

public interface ProductA //ProductA 接口 { }

public interface ProductB //ProductB 接口 { }

public class ConCreator1 implements Creator {

public ProuctA factoryA() {

return new ConcreteProductA1(); }

public ProuctB factoryB() {

return new ConcreteProductB1(); } }

public class ConCreator2 implements Creator {

public ProuctA factoryA()

3

设计模式

{

return new ProductA2(); }

public ProuctB factoryB() {

return new ProductB2(); } }

public class ProductA1 implements ProductA {

public ProductA1() { } }

public class ProductA2 implements ProductA {

public ProductA2() { } }

public class ProductB1 implements ProductB {

public ProductB1() { } }

public class ProductB2 implements ProductB {

public ProductB2() { } }

实际上是这样的

1,两个工厂类ConCreator1,ConCreator2都实现了Creator接口 2,ProuctA1,ProductA2都实现了ProductA接口 3,ProuctB1,ProductB2都实现了ProductB接口

4,ConCreator1负责生产1类型的产品(包括ProductA1,ProductB1) 5,ConCreator2负责生产2类型的产品(包括ProductA2,ProductB2)

6,工厂方法也有这样的特征,也就是说Creator不知道什么被生产出来,甚至不知道ConCreator1还是ConCreator2被实例化了,因为client高兴调那一个工厂,就调那一个工厂,就是说工厂能生产什么,对客户端是可见的。甚至还有一种情

4

设计模式

况,客户端高兴起来就生产了ProductA1,我就不生产ProductA2,因为上面的例子中它们还都是松散的,没有绑定在一起

于是提出另外一个例子,也是老提起的电脑类型的例子

1,电脑生产商是接口, 2,CUP是接口, 3,硬盘是接口,

4,IBM工厂是制造IBM品牌的电脑的工厂 5,DELL工厂是制造DEll品牌的电脑的工厂 为讨论方便,就认为电脑=CUP+硬盘;

6,所以呀CUP有IBM的CPU和DELL的CPU 7,同样硬盘也是有IBM的硬盘和DELL的硬盘

8,IBM工厂生产IBM的CPU和IBM的硬盘,绝对不生产DELL的CPU,也不生产DELL的硬盘

9,同样DELL工厂也是一样

public interface 电脑生产商 {

public CPU 制造CPU(); public 硬盘 制造硬盘(); public 电脑 制造电脑(); }

public interface CPU { }

public interface 硬盘 { }

public class IBM的CPU implements CPU {

public IBM的CPU(); }

public class IBM的硬盘 implements 硬盘 {

public IBM的硬盘();

5

设计模式

}

public class DELL的CPU implements CPU {

public DELL的CPU(); }

public class DELL的硬盘 implements 硬盘 {

public DELL的硬盘(); }

//下面是IBM工厂

public class IBM工厂 implements 电脑生产商 {

private CPU IBM的CPU私有变量=null; private 硬盘 IBM的硬盘私有变量=null; private CPU 制造CPU() {

return new IBM的CPU(); }

private 硬盘 制造硬盘() {

return new IBM的CPU(); }

public 电脑 制造电脑() { try{

IBM的CPU私有变量=this.制造CPU(); IBM的硬盘私有变量=this.制造硬盘();

if(IBM的CPU私有变量!=null&&IBM的硬盘私有变量!=null) retrun (IBM的CPU私有变量+IBM的硬盘私有变量); //组装成IBM电脑 }

catch(Exception e) {

System.out.println(\制造IBM电脑失败!\ } } } }

这样,客户端无法通过命令单生产出一个CPU来,这样抽象才真正成为一个完整产品的工厂,只要向工厂发出生产的命令,一台完整的电脑就生产出来了,而

6

设计模式

工厂怎么生产的,生产了哪些部件,外界就看不见了,外界就知道这个工厂是生产IBM电脑整机的工厂!

DELL电脑工厂一样

/**** 下面来改错, 请指出下面片段的错误*****/ public abstract class Factory{

public abstract Sample creator();

public abstract Sample2 creator(); }

public class SimpleFactory extends Factory{

public Sample creator(){ ...... }

public Sample2 creator(){ ...... } }

public class BombFactory extends Factory{

public Sample creator(){ ...... }

public Sample2 creator(){ ...... } }

思考:上面的代码错在哪??

/************ 改错结束 ***************/ 2,builder模式的理解

作者:罗鹏 Email:luopeng@ec.com.cn

7

设计模式

简单地说,就好象我要一座房子住,可是我不知道怎么盖(简单的砌墙,层次较低),也不知道怎么样设计(建几个房间,几个门好看,层次较高), 于是我需要找一帮民工,他们会砌墙,还得找个设计师,他知道怎么设计,我还要确保民工听设计师的领导,而设计师本身也不干脏活,重活,光是下命令,这里砌一堵墙,这里砌一扇门,这样民工开始建设,最后,我可以向民工要房子了。在这个过程中,设计师是什么也没有,除了他在脑子里的设计和命令,所以要房子也是跟民工要,记住了!

package builder;

public interface Builder {

public void makeWindow(); public void makeFloor(); public Room getRoom(); }

/*************************************************************/ package builder;

public class Designer {

public Designer() { }

public void order(Builder builder) //这些下等人没有知识,没有文化,哈哈,得听我的 {

builder.makeWindow(); builder.makeFloor(); }

public static void main(String[] args) { Designer designer1 = new Designer(); } }

/*************************************************************/ package builder;

public class Mingong implements Builder{ private String window=\ private String floor=\

8

设计模式

public Mingong() { }

public static void main(String[] args) { Mingong mingong1 = new Mingong(); }

public void makeWindow(){ window=new String(\ }

public void makeFloor(){ floor=new String(\ }

public Room getRoom() {

if((!window.equals(\ {

System.out.println(\ return new Room(); }

else return null; } }

/*************************************************************/ package builder; public class Room {

private String window=\ private String floor=\ public Room() { }

public static void main(String[] args) { Room room1 = new Room(); } }

/*************************************************************/

package builder;

public class Client {

public Client() { }

public static void main(String[] args) { Builder mingong=new Mingong();

Designer designer=new Designer();

9

设计模式

designer.order(mingong); mingong.getRoom(); } }

3, 适配器模式的理解

作者:罗鹏 email:luopeng@ec.com.cn public class window的软件 {

public void run(){

System.out.print(\我运行在window上\ }

public void run1(){

System.out.print(\我运行在window上的run1方法\ } }

public class linux的软件 {

public void run(){

System.out.print(\我运行在linux上\ } }

public class 适配器 extends window的软件 {

private linux的软件 软件1; //实际上是聚合的使用 public 适配器(linux的软件 软件变量) {

this.软件1= 软件变量; }

public void run() {

软件1.run(); }

public void run1() {

System.out.print(“已经被adpter改写了”); } }

客户段

10

设计模式

public class test{

public static void main(String args[]) {

linux的软件 test1=new linux的软件(); 适配器 test2=new 适配器(test1); test2.run();

test2.run1(); }

4,Memento 模式理解

作者:罗鹏 email:luopeng@ec.com.cn

Memento

帮你记住,用的时候去问一下。 就象董事长和秘书一样

public class Manage {

public String next_week; //下个星期的安排

public String n_next_week; ///下个星期的安排 public Manage() { }

public Assistant getMemento() {

return new Assistant(this); }

public void setMemento(Assistant assistant) {

next_week=assistant.next_week;

n_next_week=assistant.n_next_week; } }

public class Assistant implements java.io.Serializable { public String next_week; public String n_next_week; public Assistant(Manage manage) {

next_week=manage.next_week;

n_next_week=manage.n_next_week; } }

public class Test {

11

设计模式

public Test() { }

public static void main(String[] args) { Manage manage=new Manage(); manage.next_week=\见客户\manage.n_next_week=\见大客户\System.out.println(manage.next_week); System.out.println(manage.n_next_week); Assistant assistant=manage.getMemento(); manage.next_week=\见1111客户\

manage.n_next_week=\见111111大客户\System.out.println(manage.next_week); System.out.println(manage.n_next_week); manage.setMemento(assistant);

System.out.println(manage.next_week); System.out.println(manage.n_next_week); } }

5,state模式理解

作者:罗鹏 email: luopeng@ec.com.cn 主要是用于状态的变化,就象红绿灯一样 如何使用state模式 1,要一个状态管理类 2,状态接口

3,各种子状态实现状态接口

State模式的效果

1)它将与特定状态的行为局部化,并且将不同的行为分割开来 2)它使得状态转化显式化 3)State对象可以被共享

state模式中谁定义状态转化??

state模式中并没有指定哪一个参与者定义状态转换准则。换句话说,它们可以在Context中定义,也可以在state子类自身指定她们的后继状态以及何时进行转换,后者通常更灵活。

public interface State{

public abstract void handleGreen(State state); public abstract void handleRed(State state); public abstract State getColor(); }

12

设计模式

public class Manage { private State state=null; public Manage(State state) {

this.state=state; }

public void changeToGreen() {

this.state=new GreenLight(); state.handleGreen(state); }

public void changeToRed() {

this.state=new RedLight(); state.handleRed(state); } }

public class GreenLight implements State { public State state=null; public State getColor() {

return state; }

public void handleGreen(State state) {

System.out.println(\绿灯,前进\ }

public void handleRed(State state) {

System.out.println(\,\ } }

public class RedLight implements State { public State state=null; public State getColor() {

return state; }

public void handleGreen(State s) {

System.out.println(\

13

设计模式

}

public void handleRed(State s) {

System.out.println(\红灯,Stop!!\ } }

public class Test {

public Test() { }

public static void main(String[] args) { GreenLight state=new GreenLight(); Manage manage=new Manage(state); manage.changeToRed(); manage.changeToGreen(); manage.changeToGreen(); manage.changeToGreen(); manage.changeToRed(); } }

GOF片段赏析

1,Decrator 模式不同于Adapter模式,因为装饰仅改变对象的职责而不改变它的接口,而适配器将给对象一个全新的接口。

2,Composite模式:可以将装饰视为一个退化的、仅有一个组件的组合。然而,装饰仅给对象添加一些额外的职责---它的目的不是在于对象聚集

6,Proxy模式

public interface Subject{ publib void request(); }

public RealSubject implements Subject {

public void request(){

System.out.println(\正在处理请求!\} }

14

设计模式

public class Proxy implements Subject{ private RealSubject realSubject; public Proxy(){ }

public void request(){

if(realSubject==null){ //这里有个单例 realSubject=new RealSubject(); }

realSubject.request();

System.out.println(\哈哈,是我在处理!\ } }

public class Client {

public static void main(String args[]){ Subject subject=new Proxy();

subject.request(); //客户端没有看出来,实际上客户端发出的请求,是Proxy在处理

//正常的没有采用代理的话,代码是这个样子的 /**

Subject subject=new RealSubject(); subject.request(); **/ } }

/**思考题**/ Proxy模式

public interface Subject{ publib void request(); }

public RealSubject implements Subject {

public void request(){

System.out.println(\正在处理请求!\} }

public class Proxy implements Subject{

15

设计模式

private RealSubject realSubject; public Proxy(){ }

public void request(){

if(realSubject==null){ //这里有个单例 realSubject=new RealSubject(); }

realSubject.request();

System.out.println(\哈哈,是我在处理!\ } }

public class Client {

public static void main(String args[]){ Subject subject=new Proxy();

subject.request(); //客户端没有看出来,实际上客户端发出的请求,是Proxy在处理

//正常的没有采用代理的话,代码是这个样子的 /**

Subject subject=new RealSubject(); subject.request(); **/ } }

7,Protype模式理解

比如说有个叫张三的一个人可以复制,呵呵,他还有一本书

import java.io.*;

import java.io.Serializable;

public class Zhangsan implements Cloneable,Serializable {

public String name=\ public String name1=\ // public Book book;

public Book book=new Book(); public Zhangsan() {

this.name=\ this.book=new Book(); }

public Object clone() {

16

设计模式

try {

return super.clone(); }

catch(CloneNotSupportedException e) {

return null; } }

public Object deepClone() throws IOException,OptionalDataException,ClassNotFoundException {

ByteArrayOutputStream bo=new ByteArrayOutputStream(); ObjectOutputStream oo=new ObjectOutputStream(bo); oo.writeObject(this);

ByteArrayInputStream bi=new ByteArrayInputStream(bo.toByteArray()); ObjectInputStream oi=new ObjectInputStream(bi); return (oi.readObject()); }

public Book getBook() {

return book; }

public String getName() {

return name; } }

/**--------------------------------------------------------------------------------**/ import java.io.*;

import java.io.Serializable;

public class Zhangsan implements Cloneable,Serializable {

public String name=\ public String name1=\ // public Book book;

public Book book=new Book(); public Zhangsan() {

this.name=\ this.book=new Book(); }

public Object clone()

17

设计模式

{

try {return super.clone(); }

catch(CloneNotSupportedException e) {

return null; } }

public Object deepClone() IOException,OptionalDataException,ClassNotFoundException {

ByteArrayOutputStream bo=new ByteArrayOutputStream(); ObjectOutputStream oo=new ObjectOutputStream(bo); oo.writeObject(this);

ByteArrayInputStream bi=new ByteArrayInputStream(bo.toByteArray()); ObjectInputStream oi=new ObjectInputStream(bi); return (oi.readObject()); }

public Book getBook() {

return book; }

public String getName() {

return name; } }

/**--------------------------------------------------------------------------------**/ public class test {

public static void main(String args[]) {

Zhangsan person=new Zhangsan();

Zhangsan copy= ( Zhangsan) person.clone(); System.out.println(person.name); System.out.println(copy.name);

System.out.println(\ \ System.out.println(\of \

try {

Zhangsan deepcopy= (Zhangsan) person.deepClone(); System.out.println(\of

throws false??? false??? 18

设计模式

\ System.out.println(\of false??? \

System.out.println(\ \ System.out.println(\ \ System.out.println(person.book.pages);

System.out.println(\ \ System.out.println(deepcopy.book.pages);

System.out.println(\ \ } catch (Exception e) {

System.out.println(\ } } }

所谓clone有深clone和浅clone

博士使用的利用串行化来进行深clone,但是不能保证深clone得到的结果是正确的,这是因为有些不能串行化的,比如说,如果这个zhangsan类它继承了一个abstract class,或者implements 一些接口,而 abstract class或接口有常量等不能串行化的东西,深clone可能会失败(deepClone方法本身没有失败,可是要访问clone的对象的属性时可能会失败!)

8,composite模式理解

composite模式就是把一些具有相类似的接口的类组合起来,提供一致的访问接口

三个角色

1,抽象构件component 2,Leaf

3,树枝角色compostie

public interface Component{

public Composite getComposite(); public void mehod1(); }

import java.until.*;

public class Composite implements Component{ private Vector vector_com=new vector(); public Composite getComposite() {

return this;

19

设计模式

}

public void mehod1(){

System.out.println(\

Emumeration emumeration=vector_com.elements(); while(emumeration.hasMoreElements()){

((Component ) emumeration.nextElement()).method1(); } }

public void add(Component component) {

vector_com.add(component); }

public void remove(Component component) {

vector_com.removeElement(component); } }

public class Leaf implements Component {

public void method1() {

System.out.println(\}

public Composite getComposite() {

return null; } }

9,迭代子模式理解

/************************************************************************/

public abstract class Aggregate {

public Iterator createIterator() {

return null; } }

/********************************************************************

20

设计模式

****/

public interface Iterator { void first(); void next();

boolean isDone(); Object currentItem(); }

/************************************************************************/

public class ConcreteAggregate extends Aggregate{

private Object[] obj={\唐僧\孙悟空\猪八戒\沙僧\白龙马\妖怪\public Iterator createIterator() {

return new ConcreteIterator(this); }

public Object getElement(int index) {

if(index

public int size() {

return obj.length; } }

/************************************************************************/

public class ConcreteIterator implements Iterator {

private ConcreteAggregate agg; private int index=0; private int size=0;

public ConcreteIterator(ConcreteAggregate agg) {

this.agg=agg;

this.size=agg.size(); index=0; }

public void first(){ index=0; }

public void next(){

21

设计模式

if(index

index++; } }

public boolean isDone(){ return (index>=size); }

public Object currentItem(){ return agg.getElement(index); } }

/************************************************************************/

public class Client {

private Iterator it;

private Aggregate agg=new ConcreteAggregate(); public void operation() {

it=agg.createIterator(); while(!it.isDone()) {

System.out.println(it.currentItem().toString()); it.next(); } }

public static void main(String args[]) {

Client client=new Client(); client.operation(); } }

10,bridge模式理解

public abstract class Airplane {

public sbstract void fly();

protected AirplaneMaker airplaneMaker; //桥在哪??桥在这里!! }

22

设计模式

public class PassengerPlane extends Airplane {

public void fly() {

System.out.println(\ } }

public CargoPlane Extends Airplane {

public void fly() {

System.out.println(\ } }

public abstract class AirplaneMaker {

public abstract void produce(); }

public class Airbus extends AirplaneMaker{ public void produce() {

System.out.println(\} }

public class Boeing extends AirplaneMaker{ public void produce() {

System.out.println(\} }

public class MD extends AirplaneMaker{ public void produce() {

System.out.println(\ produce\} }

public class test {

23

设计模式

public static void main(String args[]) {

PassengerPlane plane=new PassengerPlane(); plane.airplaneMaker=new MD(); plane.airplaneMaker.produce();

plane.airplaneMaker=new Airbus();

//之所以能变化,是因为桥这里可以重新选择制造商 plane.airplaneMaker.produce(); } }

使用此模式的前提是客户端并不深究得到的产品是抽象的n维(本例子里是2维)和行为的m维(本例子里是2维)这n*m中的具体那一种,行为那边的变化也只是m个变化,实际上一个具体一个行为只有一个确定的形式,之所以能够变化是抽象它有m个具体行为可以选择!

换句话说,这个桥他是单向的,只能从抽象这一头度到行为那一头!

public CargoPlane Extends Airplane {

public void fly() {

System.out.println(\ //

//这里可以进行一些委派 , airplaneMaker.produce(); //但是反过来不行 } }

11,责任链模式

解释:在一个公司的管理系统中,可以自己申请加薪。

比如你对你的工资不满意,要求申请加薪,但是本部门,行政部,和总裁办都可以给员工加薪,但是加薪的幅度有大有小,你可以向你本部门申请加薪,比如我在技术部

技术部最多给员工加500元,如果小于500,本部门就可以自己执行。如果员工申请的数量大于1000,就要由行政部执行! 如过大于2000,就要由总裁办执行!!

package cor;

public abstract class Dept { protected Dept successor;

public abstract void addSalary(int money); public Dept getSuccessor(){

24

设计模式

return this.successor; }

public void SetSuccessor(Dept dept){ this.successor=dept; } }

/************************************************/ package cor;

public class TechDept extends Dept { //protected Dept successor;

public void addSalary(int money) { if(money > 500){

System.out.println(\转发admin:salary\ this.getSuccessor().addSalary(2500); }else{

addSalary(money); } } }

/************************************************/ package cor;

public class AdminDept extends Dept { //protected Dept successor;

public void addSalary(int money) { if(money > 1000){

System.out.println(\转发pres\ getSuccessor().addSalary(2500); }else{

addSalary(money); } } }

/************************************************/

package cor;

25

设计模式

public class President extends Dept { //protected Dept successor;

public void addSalary(int money) { if(money> 2000){

System.out.println(\处理\ // addSalary();

// System.out.println(\加完后的薪水\ } }

/************************************************/

package cor;

public class Main {

public Main() { }

public static void main(String[] args) { Dept pre = new President();

Dept admin = new AdminDept(); Dept dept = new TechDept(); dept.SetSuccessor(admin); admin.SetSuccessor(pre); dept.addSalary(2500); } }

12,Observer模式理解

import java.util.*;

public abstract class Subject {

private Vector observers_vector=new Vector(); public void add_ob(Observer observer) {

observers_vector.add(observer); }

public void remove_from(Observer observer) {

observers_vector.remove(observer); }

public void notify_all()

26

设计模式

{

Enumeration enumeration=observers_vector.elements(); while(enumeration.hasMoreElements()) {

((Observer)enumeration.nextElement()).update(); } } }

public class ConcreteSubject extends Subject {

private String state;

public void change(String newState) {

this.state=newState; this.notify_all(); } }

public class ConcreteObserver implements Observer {

public void update() {

System.out.println(\ } }

public class Client {

public static void main(String args[]) {

ConcreteSubject subject=new ConcreteSubject(); Observer observer=new ConcreteObserver(); subject.add_ob(observer);

subject.change(\} }

13,Visitor模式理解

---------------------------------------------------------------------------- public interface Visitor {

void visit(Node1 node);

void visit(Node2 node);

27

设计模式

}

---------------------------------------------------------------------------- public class Visitor1 implements Visitor {

public void visit(Node1 node1) {

node1.operation1(); }

public void visit(Node2 node2) {

node2.operation2(); } }

---------------------------------------------------------------------------- public class Visitor2 implements Visitor {

public void visit(Node1 node1) {

node1.operation1(); }

public void visit(Node2 node2) {

node2.operation2(); } }

----------------------------------------------------------------------------

public interface Node {

public void accept(Visitor visitor); }

---------------------------------------------------------------------------- public class Node1 impelments Node {

public void accept(Visitor visitor) {

visitor.visit(this); }

public void operation1() {

System.out.println(\

28

设计模式

} }

---------------------------------------------------------------------------- public class Node2 impelments Node {

public void accept(Visitor visitor) {

visitor.visit(this); }

public void operation2() {

System.out.println(\ } }

---------------------------------------------------------------------------- import java.util.*;

public class Structure {

private Vector node_list= new Vector();;

/**

* @link aggregation */

private Node node;

public Structure() { }

public void action(Visitor visitor) {

for(Enumeration e = node_list=.elements(); e.hasMoreElements();) {

node = (Node)e.nextElement(); node.accept(visitor); } }

public void add(Node node) {

29

设计模式

node_list.addElement(node); } }

---------------------------------------------------------------------------- public class Client {

private static Structure structure; private static Visitor visitor;

public static void main(String[] args) {

structure = new Structure();

structure.add(new Node1()); structure.add(new Node1());

visitor = new Visitor1(); structure.action(visitor);

} } 练习

1,用composite模式写一个二叉树的例子

package binarytree;

public abstract class Component { private String name;

public abstract Component addChild(Component leftChild,Component rightChild); //public abstract Component addLeftChild(Component leftChild); public String getName(){return name;} public void getTreeInfo(){}

public abstract int getLength(); }

/***********************************************/

package binarytree;

public class Tree extends Component { private String name;

30

设计模式

private Component leftChild; private Component rightChild;

public Tree(String name,Component leftChild,Component rightChild) { this.name=name;

this.leftChild=leftChild; this.rightChild=rightChild; }

public Tree(String name) { this.name=name; this.leftChild=null; this.rightChild=null; }

public Component addChild(Component leftChild,Component rightChild){ this.leftChild=leftChild; this.rightChild=rightChild; return this; }

public String getName(){ return name; }

public void getTreeInfo() {

System.out.println(\ if(this.leftChild instanceof Leaf) {

System.out.println(getName()+\\a Leaf\ }

if(this.leftChild instanceof Tree){

System.out.println(getName()+\\a Tree\

this.leftChild.getTreeInfo(); }

if(this.leftChild==null) {

System.out.println(getName()+\ }

if(this.rightChild instanceof Leaf) {

System.out.println(getName()+\is a Leaf\ }

if(this.rightChild instanceof Tree) {

System.out.println(getName()+\

31

设计模式

is a Tree\

this.rightChild.getTreeInfo(); }

if(this.rightChild==null) {

System.out.println(getName()+\ }

//System.out.println(getName()+\高度 是 \ }

public int getLength() { if(this.leftChild==null) { if(this.rightChild==null) return 1; else

return this.rightChild.getLength()+1; } else {

if(this.rightChild==null) {

return this.leftChild.getLength()+1; } else {

if((this.leftChild.getLength())>=(this.rightChild.getLength())) return this.leftChild.getLength()+1; else

return this.rightChild.getLength()+1; } } }

public static void main(String[] args) { } }

/*******************************************/

package binarytree;

public class Leaf extends Component{ private String name;

private Component leaf=null; public Leaf(String name) { this.name=name; }

public Component addLeftChild(Component leftChild){

32

设计模式

return this; }

public Component addRightChild(Component rightChild){ return this; }

public Component addChild(Component leftChild,Component rightChild){ return this; }

public String getName(){ return name; }

public int getLength() { return 1; }

public static void main(String[] args) { // Leaf leaf1 = new Leaf(); } }

/*********************************************************/

package binarytree;

public class Test {

public Test() { }

public static void main(String[] args) { Component tree=new Tree(\

Component leaf_child=new Leaf(\ Component right_child=new Leaf(\ tree=tree.addChild(leaf_child,right_child); //tree=tree.addRightChild(right_child); tree.getTreeInfo();

Component tree1=new Tree(\ tree1.addChild(tree,leaf_child); tree1.getTreeInfo();

Component tree2=new Tree(\ tree2.addChild(tree,null); tree2.getTreeInfo();

Component tree4=new Tree(\ tree4.addChild(null,tree); tree4.getTreeInfo();

System.out.println(tree4.getName()+\ \

33

设计模式

} }

14, Mediator 模式理解

用于一系列关于对象交互行为,用一个中介对象

public interface Mediator{ }

public class ConcreateMediator implements Midiator{ private Member m1=new ConcreateMember1(); private Member m2=new ConcreateMember2(); public void operation{

//比如说把m1的成员变量和m2的成员变量互换 } }

public class Member{

private Mediator mediator; public Mddiator getMediator() {

return mediator; }

public void setMediator(Mediator mediator)

this.mediator=mediator; }

public class ConcreateMember1 extends Member{ }

public class ConcreateMember2 extends Member{ }

/******************************/ GOF经典赏析 模式与多态

Factory Method实现了创建的多态 Prototype实现了拷贝的多态

34

设计模式

。Builder实现了创建过程的多态

/******************************/ GOF片段赏析

1,Decrator 模式不同于Adapter模式,因为装饰仅改变对象的职责而不改变它的接口,而适配器将给对象一个全新的接口。

2,Composite模式:可以将装饰视为一个退化的、仅有一个组件的组合。然而,装饰仅给对象添加一些额外的职责---它的目的不是在于对象聚集

3,Strategy模式:用一个装饰你可以改变对象的外壳,而Strategy模式使得你可以改变对象的内核,这是改变对象的两种途径。

/*******************************/ 15.singleton 模式该错

以下说法有什么错误??

Singleton模式:

Singleton模式主要作用是保证在Java应用程序中,一个Class只有一个实例存在。

一般有三种方法:

1 定义一个类,它的构造函数为private的,所有方法为static的。如java.lang.Math

其他类对它的引用全部是通过类名直接引用。例如: public final class Math { /**

* Don't let anyone instantiate this class. */

private Math() {}

public static int round(float a) { return (int)floor(a + 0.5f); } ... }

2 定义一个类,它的构造函数为private的,它有一个static的private的该类变量,在类初始化时

实例话,通过一个public的getInstance方法获取对它的引用,继而调用其中的方法。例如:

public class Runtime {

35

设计模式

private static Runtime currentRuntime = new Runtime();

public static Runtime getRuntime() { return currentRuntime; } ... }

3 定义一个类,它的构造函数为private的,它有一个static的private的boolean变量,用于表示

是否有实例存在。例如:

class PrintSpooler {

//this is a prototype for a printer-spooler class //such that only one instance can ever exist static boolean

instance_flag=false; //true if 1 instance

public PrintSpooler() throws SingletonException {

if (instance_flag)

throw new SingletonException(\ else

instance_flag = true; //set flag for 1 instance System.out.println(\ }

//------------------------------------------- public void finalize() {

instance_flag = false; //clear if destroyed }

}

/**************** 改错结束 ******************/ 面向对象的原则

1,The Open/Closed Principle (OCP) 2,The Liskov Substitution Principle (LSP) 3,The Dependency Inversion Principle (DIP) 4,The Interface Segregation Principle (ISP)

5,The Reuse/Release Equivalency Principle (REP) 6,The Common Closure Principle (CCP) 7,The Common Reuse Principle (CRP)

36

设计模式

8,The Acyclic Dependencies Principle (ADP) 9,The Stable Abstractions Principle (SAP)

37

本文来源:https://www.bwwdw.com/article/aat3.html

Top