总结设计模式—(大话设计模式下篇)

1、迭代器模式  通过此模式我们可以遍历数组和集合

 interface Iterator {

     public boolean hasNext();
     public Object next();
 }

class ConcreteIterator implements Iterator {
    private List list = null;
    private int index;

    public ConcreteIterator(List list) {
        super();
        this.list = list;
    }

    public boolean hasNext() {
        if (index >= list.getSize()) {
            return false;
        } else {
            return true;
        }
    }

    public Object next() {
        Object object = list.get(index);
        index++;
        return object;
    }

}

 interface List {
    public void add(Object obj);  
    public Object get(int index);
    public Iterator iterator();  
    public int getSize();
}
class ConcreteAggregate implements List{

    private Object[] list;
    private int size=0;
    private int index=0;
    public ConcreteAggregate(){
        index=0;
        size=0;
        list=new Object[100];
    }

    public void add(Object obj) {
        list[index++]=obj;
        size++;
    }


    public Iterator iterator() {
        return new ConcreteIterator(this);
    }
 
    public Object get(int index) { 
        return list[index];
    }
  
    public int getSize() {   
        return size;
    }

}

public class IteratorTest {

    public static void main(String[] args) {
        List list=new ConcreteAggregate();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        Iterator it=list.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }

}

  像Java中的集合list、set、map都有继承Iterable(迭代)接口。

 

2、单例模式  频繁的进行创建和销毁的对象会造成内存的浪费

  推荐代码示例1

public class Singleton {
  //属性需要不公开
    private static volatile Singleton singleton;
  //构造器需要private
    private Singleton() {}

    public static Singleton getInstance() {
        if (singleton == null) {
  //同步
synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }

   推荐代码示例2

public class Singleton {

    private Singleton() {}
//静态内部类
    private static class SingletonInstance {
        private static final Singleton INSTANCE = new Singleton();
    }
//只有调用getInstance 才装载SingletonInstance类
public static Singleton getInstance() { return SingletonInstance.INSTANCE; } }

 

3、桥接模式 显示类的合成和聚合关系:合成指的是类拥有的关系,相当于拥有某个属性,聚合就是类继承。我的理解就是策略模式的延伸。

  手写代码,未测过,呵呵呵      

class Extends{

    Bridge  bridge;
    Extends(Bridge  bridge){
        this.bridge = bridge;
    }
    
    void method(){
        bridge.method();
    }
}

class ExtendsA extends Extends{
    void method(){
        bridge.method();
    }
}
class ExtendsB extends Extends{
    void method(){
        bridge.method();
    }
}

interface Bridge{
    void method();
}

class BridgeA implements Bridge{
    void method(){
        System.out.println("添加桥A");
    }
}
class BridgeB implements Bridge{
    void method(){
        System.out.println("添加桥B");
    }
}

public static void main(String[] args){
    Extends extends;
    extends = new ExtendsA(new BridgeA)
    extends.method();
    extends = new ExtendsA(new BridgeB)
    extends.method();
}

 

 4、命令模式 此模式感觉就像是桥接模式+桥接模式,命令模式趋向于做多个命令

    策略模式 ->  桥接模式   ->  命令模式       由少到多到更多。呵呵呵。。。

 5、职责链模式 上面模式的添加方法,添加类属性,如果添加的是自己类作为一个属性放入类中嵌套就是 职责链。    

abstract class DutyChain{
    protected DutyChain duty;     
    public void setDuty(DutyChain dutyChain) { 
        this.duty = dutyChain ;
    }
    abstract void method();

}

  

 6、中介者模式  我觉得中介者模式就是策略模式延伸过来,类可以嵌套多个其他类属性,在中介者中调节

public class MediatorPattern {

	public static void main(String[] args) {
		UnitedNationsSecurityCouncil UNSC = new UnitedNationsSecurityCouncil();
		USA c1 = new USA(UNSC);
		Iraq c2 = new Iraq(UNSC);
		UNSC.setColleague1(c1);
		UNSC.setColleague2(c2);
		c1.declare("不准研发核武器,否则发动战争");
		c2.declare("我们没有核武器,也不怕侵略。");
	}

}

abstract class UnitedNations{
	public abstract void declare(String message,Country colleague);
}

abstract class Country{
	protected UnitedNations mediator;

	public Country(UnitedNations mediator) {
		this.mediator = mediator;
	}
}

class USA extends Country{
	public USA(UnitedNations mediator) {
          //这个不能丢 super(mediator); } // 声明 public void declare(String message){ mediator.declare(message,this); } // 获得消息 public void GetMessage(String message){ System.out.println( "美国获得对方信息: " + message ); } } class Iraq extends Country{ public Iraq(UnitedNations mediator) { super(mediator); } public void declare(String message) { mediator.declare(message, this); } public void GetMessage(String message){ System.out.println( "伊拉克获得对方信息: " + message ); } } class UnitedNationsSecurityCouncil extends UnitedNations{      //嵌套两个类属性 private USA colleague1; private Iraq colleague2; public USA getColleague1() { return colleague1; } public void setColleague1(USA colleague1) { this.colleague1 = colleague1; } public Iraq getColleague2() { return colleague2; } public void setColleague2(Iraq colleague2) { this.colleague2 = colleague2; } //类中调节 public void declare(String message, Country colleague) { if (colleague == colleague1){ colleague2.GetMessage(message); }else{ colleague1.GetMessage(message); } } }

  运行结果

      伊拉克获得对方信息: 不准研发核武器,否则发动战争

      美国获得对方信息: 我们没有核武器,也不怕侵略。

* 优点:
   简化了对象之间的交互:它用中介者和同事的一对多交互代替了原来同事之间的多对多交互,一对多关系更容易理解、维护和扩展,
将原本难以理解的网状结构转换成相对简单的星型结构。
  各同事对象之间解耦:中介者有利于各同事之间的松耦合,我们可以独立的改变和复用每一个同事和中介者,增加新的中介者和新的
同事类都比较方便,更好地符合“开闭原则”。
  减少子类生成:中介者将原本分布于多个对象间的行为集中在一起,改变这些行为只需生成新的中介者子类即可,这使各个同事类可
被重用,无须对同事类进行扩展。
缺点:
  中介者会庞大,变得复杂难以维护。

7、 享元模式   将对象放入集合中,通过对对象的集合操作,减少大量对象的存储开销。 

class Water{
    private String name;

    public Water(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

}

interface Clouds{
    public void method( Water water);
}

class WhiteClouds implements Clouds{
    private String name;

    public WhiteClouds(String name) {
        this.name = name;
    }
    @Override
    public void method( Water water) {
        System.out.println(" 白云飘飘 : " + this.name+",云撑:"+water.getName());
    }
}

class BlackClouds implements Clouds{

    @Override
    public void method( Water water) {
        System.out.println(" 黑云滚滚 : " + water.getName());
    }
}
public class EnjoyClouds {

    private static final Map<String,Clouds> map = new HashMap<String, Clouds>();

    public  Clouds getClouds(String key){
        if(!map.containsKey(key)){
            map.put(key,new WhiteClouds(key));
        }
//        Clouds clouds = map.get(key);
//        if (clouds == null){
//            map.put(key,new WhiteClouds(key));
//        }
        return map.get(key);
    }

    public int getCount(){
        return map.size();
    }

    public static void main(String[] args) {
        EnjoyClouds enjoyClouds = new EnjoyClouds();
        String key = "小白";
        Water water = new Water("大鱼");
        Clouds clouds = enjoyClouds.getClouds( key );
        clouds.method(water);
        clouds = map.get( key );
        clouds.method(new Water("小虾"));
        System.out.println( enjoyClouds.getCount() );
    }

}

8、解释者模式  需要解释执行并且可以将该语言中的语句表示为一个可执行语句

  

/**解释模式
 * 用解释器模式来实现 加减乘除四则运算
 * Created by nicknailo on 2018/8/30.
 */
public class InterpretPattern {

    public static void main(String[] args) {
        Calculator calculator = new Calculator("123 + 124 + 125 - 126");
        System.out.println(calculator.calculate());


    }

}

abstract class ArithmeticExpression {
    public abstract int interptet();
}

class NumExpression extends ArithmeticExpression {
    private int num;
    public NumExpression(int _num) {
        num = _num;
    }
    @Override
    public int interptet() {
        return num;
    }
}

abstract class OperatorExpression extends ArithmeticExpression {
    protected ArithmeticExpression mArithmeticExpression1,mArithmeticExpression2;

    public OperatorExpression(ArithmeticExpression _arithmeticExpression1, ArithmeticExpression _arithmeticExpression2) {
        mArithmeticExpression1 = _arithmeticExpression1;
        mArithmeticExpression2 = _arithmeticExpression2;
    }
}

class AdditionExpression extends OperatorExpression {
    public AdditionExpression(ArithmeticExpression _arithmeticExpression1, ArithmeticExpression _arithmeticExpression2) {
        super(_arithmeticExpression1, _arithmeticExpression2);
    }

    @Override
    public int interptet() {
        return mArithmeticExpression1.interptet() + mArithmeticExpression2.interptet();
    }
}

class PlusExpression extends OperatorExpression {
    public PlusExpression(ArithmeticExpression _arithmeticExpression1, ArithmeticExpression _arithmeticExpression2) {
        super(_arithmeticExpression1, _arithmeticExpression2);
    }

    @Override
    public int interptet() {
        return mArithmeticExpression1.interptet() - mArithmeticExpression2.interptet();
    }
}


class Calculator {

    protected Stack<ArithmeticExpression> mArithmeticExpressionStack = new Stack<ArithmeticExpression>();

    public Calculator(String expression) {
        ArithmeticExpression arithmeticExpression1, arithmeticExpression2;
        String[] elements = expression.split(" ");
        for (int i = 0; i < elements.length; ++i) {
            System.out.println("elements: " + Arrays.toString(elements));
            System.out.println("elements[i]: " + elements[i].charAt(0));
            switch (elements[i].charAt(0)) {
                case '+':
                    arithmeticExpression1 = mArithmeticExpressionStack.pop();
                    System.out.println("stack.pop : = "+ arithmeticExpression1.interptet());
                    arithmeticExpression2 = new NumExpression(Integer.valueOf(elements[++i]));
                    mArithmeticExpressionStack.push(
                            new AdditionExpression(arithmeticExpression1, arithmeticExpression2));
                    break;
                case '-':
                    arithmeticExpression1 = mArithmeticExpressionStack.pop();
                    System.out.println("stack.pop : = "+ arithmeticExpression1.interptet());
                    arithmeticExpression2 = new NumExpression(Integer.valueOf(elements[++i]));
                    mArithmeticExpressionStack.push(
                            new PlusExpression(arithmeticExpression1, arithmeticExpression2));
                    break;
                default:
                    mArithmeticExpressionStack.push(new NumExpression(Integer.valueOf(elements[i])));
                    break;
            }
        }
    }

    public int calculate() {
        return mArithmeticExpressionStack.pop().interptet();
    }
}

 

9、访问者模式 点击查看 

 

posted @ 2018-10-30 16:46  nicknailo  阅读(246)  评论(0编辑  收藏  举报