您的位置:首页 > 编程语言

23种设计模式及简单代码

2014-09-11 09:57 465 查看

1. 概述

随着做项目增多不可避免地接触到了设计模式,现在各大文档中呈现的设计模式总共有23种,实际上使用中的肯定比23种多,为了让自己深刻理解设计模式,本博决定自己手写这些设计模式,便于在项目中灵活使用。

设计模式又称为GOF(gang of four四个作者的情切称呼),读完GOF印象最深的就是“解耦”二字,就像“狂人日记”满篇充斥着两个字“吃人”,GOF满篇蕴含着两个字“解耦”。实际上这也是GOF存在的意义,将软件模块化,尽可能减少模块之间的联系,实现软件功能模块最大限度的重用性,减少程序员重复做轮子的工作;本博认为,设计模式的出现是将工业流水线工作的模式和建筑设计思想引入了软件生产中,给编程过程中遇到的问题提供了若干种设计方式,将软件生产过程分解为多个模块,每个模块间互不相干,但模块的综合却能完成复杂的工作;这就使设计模式的意义所在。

2. 23种设计模式

做事情要讲究目的和意义,否则就是在浪费时间,上面探讨了GOF的存在目的和意义,现在多说无益,直接上模式:

2.1 工厂方法模式

工厂方法模式将生成实例的功能给工厂子类,每个子类都只返回单一的实例对象。
<pre name="code" class="java">public abstract class Animal{}
public Dog extends Animal{}
public Cat extends Animal{}
public abstract class AnimalFactory{
    public abstract Animal  getAnimal();
}
public class CatFactory implements AnimalFactory{
    public Animal getAnimal(){
    System.out.println("cat");
    return new Cat();
    }
}
public class DogFactory implements Animal{
    public Animal getAnimal(){
    System.out.println("dog");
    return new Dog();
    }
}
public class TestFactory{
    public static void main(){
    AnimalFactory af = new CatFactory();
    Animal cat = af.getAnimal();
    }
}






2.2 抽象工厂模式

抽象工厂模式是将具体生成类实例的功能让子类来完成,子类能完成多个实例的生成。
<pre name="code" class="java">public abstract class Animal{};
public class Cat extends Animal{};
public class Dog extends Animal{};
public abstract class Fruit{};
public class Apple extends Fruit{};
public class Orange extends Fruit{};
public abstract class Factory{
    public abstract Animal getCat();
    public abstract Animal getDog();
    public abstract Fruit getApple();
    public abstract Fruit getOrange();
}
public class AnimalFactory extends Factory{
    public Animal getCat(){
    return new Cat();
    }
    public Animal getDog(){
    return new Dog();
    }
}
public class FruitFactory extends Factory{
    public Fruit getApple(){
    return Apple();
    }
    public Fruit getOrange(){
    return Orange();
    }
}
public class TestFactory{
    public static void main(){
    Factory af = new AnimalFactory();
    Animal cat = af.getCat();
    Animal dog = af.getDog();
    Factory ff = new FruitFactory();
    Fruit apple = ff.getApple();
    ...
    }
}




2.3 单例模式singleton

2.4 原型模式prototype

2.5 建造模式builder

2.6 适配器模式adapter

2.7 代理模式proxy

2.8 门面模式facet

2.9 组合模式composite

2.10 装饰器模式decorator

2.11 桥连模式bridge

2.12 共享元模式flyweight

2.13 命令模式command

2.14 观察者模式observer

2.15 模板模式template

2.16 策略模式strategy

2.17 责任链模式chain of responsibility

2.18 中介模式mediator

2.19 状态模式state

2.20 memento模式

2.21 解释器模式interpreter

2.22 访问者模式visitor

2.23 迭代器模式iterator

目录先写这儿晚上更新 :)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: