创建模式

1.工厂方法模式(Factory Method)  将程序中创建对象的操作,单独出来处理,创建一个产品的工厂接口,把实际的工作转移到详细的子类。大大提高了系统扩展的柔性,接口的抽象化处理给相互依赖的对象创建提供了最好的抽象模式。

  1. public class TestFactoryMethod {
  2.  
  3. public static void main(String[] args) {
  4.  
  5. AnimalFactory af=new DogFactory();
  6.  
  7. Animal1 a=af.getAnimal();
  8.  
  9. }
  10.  
  11. }
  12.  
  13. abstract class Animal1{}
  14.  
  15. class Dog1 extends Animal1{}
  16.  
  17. class Cat1 extends Animal1{}
  18.  
  19. abstract class AnimalFactory{
  20.  
  21. public abstract Animal1 getAnimal();
  22.  
  23. }
  24.  
  25. class DogFactory extends AnimalFactory{
  26.  
  27. public Animal1 getAnimal(){
  28.  
  29. System.out.println("Dog");
  30.  
  31. return new Dog1();
  32.  
  33. }
  34.  
  35. }
  36.  
  37. class CatFactory extends AnimalFactory{
  38.  
  39. public Animal1 getAnimal(){
  40.  
  41. System.out.println("Cat");
  42.  
  43. return new Cat1();
  44.  
  45. }
  46.  
  47. }

2.抽象工厂模式(Abstract Factory) 针对多个产品等级的情况,而工厂方法模式针对单一产品等级的情况。

  1. import java.awt.*;
  2.  
  3. import javax.swing.*;
  4.  
  5. import java.awt.event.*;
  6.  
  7. public class TestAbstractFactory {
  8.  
  9. public static void main(String[] args) {
  10.  
  11. GUIFactory fact=new SwingFactory();
  12.  
  13. Frame f=fact.getFrame();
  14.  
  15. Component c1=fact.getButton();
  16.  
  17. Component c2=fact.getTextField();
  18.  
  19. f.setSize(500,300);
  20.  
  21. f.setLayout(new FlowLayout());
  22.  
  23. f.add(c1);
  24.  
  25. f.add(c2);
  26.  
  27. f.setVisible(true);
  28.  
  29. f.addWindowListener(new WindowAdapter(){
  30.  
  31. public void windowClosing(WindowEvent e){
  32.  
  33. System.exit(0);
  34.  
  35. }
  36.  
  37. });
  38.  
  39. }
  40.  
  41. }
  42.  
  43. abstract class GUIFactory{
  44.  
  45. public abstract Component getButton();
  46.  
  47. public abstract Component getTextField();
  48.  
  49. public abstract Frame getFrame();
  50.  
  51. }
  52.  
  53. class AWTFactory extends GUIFactory{
  54.  
  55. public Component getButton() {
  56.  
  57. return new Button("AWT Button");
  58.  
  59. }
  60.  
  61. public Frame getFrame() {
  62.  
  63. return new Frame("AWT Frame");
  64.  
  65. }
  66.  
  67. public Component getTextField() {
  68.  
  69. return new TextField(20);
  70.  
  71. }
  72.  
  73. }
  74.  
  75. class SwingFactory extends GUIFactory{
  76.  
  77. public Component getButton() {
  78.  
  79. return new JButton("Swing Button");
  80.  
  81. }
  82.  
  83. public Frame getFrame() {
  84.  
  85. return new JFrame("Swing Frame");
  86.  
  87. }
  88.  
  89. public Component getTextField() {
  90.  
  91. return new JTextField(20);
  92.  
  93. }
  94.  
  95. }

3.单例模式(Singleton) 改善全局变量和命名空间的冲突,能够说是一种改良了的全局变量。这样的一个类仅仅有一个实例,且提供一个訪问全局点的方式,更加灵活的保证了实例的创建和訪问约束。系统中仅仅有一个实例,因此构造方法应该为私有 饿汉式:类载入时直接创建静态实例 懒汉式:第一次须要时才创建一个实例,那么newInstance方法要加同步 饿汉式比懒汉式要好,虽然资源利用率要差。可是不用同步。

  1. public class TestSingleton {
  2.  
  3. public static void main(String[] args) {
  4.  
  5. }
  6.  
  7. }
  8.  
  9. class ClassA{ //饿汉式
  10.  
  11. private static ClassA i=new ClassA();
  12.  
  13. public static ClassA newInstance(){
  14.  
  15. return i;
  16.  
  17. }
  18.  
  19. private ClassA(){}
  20.  
  21. }
  22.  
  23. class ClassB{ //懒汉式
  24.  
  25. private static ClassB i=null;
  26.  
  27. public static synchronized ClassB newInstance(){
  28.  
  29. if (i==null) i=new ClassB();
  30.  
  31. return i;
  32.  
  33. }
  34.  
  35. private ClassB(){}
  36.  
  37. }

4.建造模式(Builder) 将一个对象的内部表象和建造过程切割,一个建造过程能够造出不同表象的对象。可简化为模版方法模式.

  1. public class TestBuilder {
  2.  
  3. public static void main(String[] args) {
  4.  
  5. Builder b=new BuilderImpl1();
  6.  
  7. Director d=new Director(b);
  8.  
  9. Product p=d.createProduct();
  10.  
  11. }
  12.  
  13. }
  14.  
  15. interface Builder{
  16.  
  17. void buildPart1();
  18.  
  19. void buildPart2();
  20.  
  21. void buildPart3();
  22.  
  23. Product getProduct();
  24.  
  25. }
  26.  
  27. class BuilderImpl1 implements Builder{
  28.  
  29. public void buildPart1() {
  30.  
  31. System.out.println("create part1");
  32.  
  33. }
  34.  
  35. public void buildPart2() {
  36.  
  37. System.out.println("create part2");
  38.  
  39. }
  40.  
  41. public void buildPart3() {
  42.  
  43. System.out.println("create part3");
  44.  
  45. }
  46.  
  47. public Product getProduct() {
  48.  
  49. return new Product();
  50.  
  51. }
  52.  
  53. }
  54.  
  55. class Director{
  56.  
  57. Builder b;
  58.  
  59. public Director(Builder b){
  60.  
  61. this.b=b;
  62.  
  63. }
  64.  
  65. public Product createProduct(){
  66.  
  67. b.buildPart1(); b.buildPart2();
  68.  
  69. b.buildPart3();
  70.  
  71. return b.getProduct();
  72.  
  73. }
  74.  
  75. }
  76.  
  77. class Product{}

5.原型模式(ProtoType) 通过一个原型对象来创建一个新对象(克隆)。Java中要给出Clonable接口的实现,详细类要实现这个接口,并给出clone()方法的实现细节,这就是简单原型模式的应用。  浅拷贝:仅仅拷贝简单属性的值和对象属性的地址  深拷贝:拷贝本对象引用的对象,有可能会出现循环引用的情况。能够用串行化解决深拷贝。写到流里再读出来,这时会是一个对象的深拷贝结果。

  1. import java.io.*;
  2.  
  3. public class TestClonealbe {
  4.  
  5. public static void main(String[] args) throws Exception {
  6.  
  7. Father f=new Father();
  8.  
  9. User u1=new User("123456",f);
  10.  
  11. User u2=(User)u1.clone();
  12.  
  13. System.out.println(u1==u2);
  14.  
  15. System.out.println(u1.f==u2.f);
  16.  
  17. }
  18.  
  19. }
  20.  
  21. class User implements Cloneable,Serializable{
  22.  
  23. String password;
  24.  
  25. Father f;
  26.  
  27. public User(String password,Father f){
  28.  
  29. this.password=password;
  30.  
  31. this.f=f;
  32.  
  33. }
  34.  
  35. public Object clone() throws CloneNotSupportedException {
  36.  
  37. //return super.clone();
  38.  
  39. ObjectOutputStream out=null;
  40.  
  41. ObjectInputStream in=null;
  42.  
  43. try {
  44.  
  45. ByteArrayOutputStream bo=new ByteArrayOutputStream();
  46.  
  47. out = new ObjectOutputStream(bo);
  48.  
  49. out.writeObject(this);
  50.  
  51. out.flush();
  52.  
  53. byte[] bs=bo.toByteArray();
  54.  
  55. ByteArrayInputStream bi=new ByteArrayInputStream(bs);
  56.  
  57. in = new ObjectInputStream(bi);
  58.  
  59. Object o=in.readObject();
  60.  
  61. return o;
  62.  
  63. } catch (IOException e) {
  64.  
  65. e.printStackTrace();
  66.  
  67. return null;
  68.  
  69. } catch (ClassNotFoundException e) {
  70.  
  71. e.printStackTrace();
  72.  
  73. return null;
  74.  
  75. }
  76.  
  77. finally{
  78.  
  79. try {
  80.  
  81. out.close();
  82.  
  83. in.close();
  84.  
  85. } catch (IOException e) {
  86.  
  87. e.printStackTrace();
  88.  
  89. }
  90.  
  91. }
  92.  
  93. }
  94.  
  95. }
  96.  
  97. class Father implements Serializable{}

结构模式 怎样把简单的类依据某种结构组装为大的系统

6.适配器模式(Adapter) 在原类型不做不论什么改变的情况下,用一个适配器类把一个接口转成还有一个接口,扩展了新的接口,灵活且多样的适配一切旧俗。这样的打破旧框框,适配新格局的思想,是面向对象的精髓。以继承方式实现的类的 Adapter模式和以聚合方式实现的对象的Adapter模式,各有千秋,各取所长。

  1. public class TestAdapter {
  2.  
  3. public static void main(String[] args) {
  4.  
  5. USB mouse=new Mouse();
  6.  
  7. PC pc=new PC();
  8.  
  9. //pc.useMouse(mouse);
  10.  
  11. PS2 adapter=new USB2PS2Adapter(mouse);
  12.  
  13. pc.useMouse(adapter);
  14.  
  15. }
  16.  
  17. }
  18.  
  19. interface PS2{
  20.  
  21. void usePs2();
  22.  
  23. }
  24.  
  25. interface USB{
  26.  
  27. void useUsb();
  28.  
  29. }
  30.  
  31. class Mouse implements USB{
  32.  
  33. public void useUsb(){
  34.  
  35. System.out.println("通过USB接口工作");
  36.  
  37. }
  38.  
  39. }
  40.  
  41. class PC{
  42.  
  43. public void useMouse(PS2 ps2Mouse){
  44.  
  45. ps2Mouse.usePs2();
  46.  
  47. }
  48.  
  49. }
  50.  
  51. class USB2PS2Adapter implements PS2{
  52.  
  53. private USB usb;
  54.  
  55. public USB2PS2Adapter(USB usb) {
  56.  
  57. this.usb = usb;
  58.  
  59. }
  60.  
  61. public void usePs2(){
  62.  
  63. System.out.println("把对usePS2的方法调用转换成对useUSB的方法调用");
  64.  
  65. usb.useUsb();
  66.  
  67. }
  68.  
  69. }

7.组合模式(Composite) 把总体和局部的关系用树状结构描写叙述出来,使得client把总体对象和局部对象同等看待。

  1. import java.util.*;
  2.  
  3. public class TestComposite {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. Node n1=new LeafNode(3);
  8.  
  9. Node n2=new LeafNode(4);
  10.  
  11. Node n3=new LeafNode(6);
  12.  
  13. Node n4=new LeafNode(5);
  14.  
  15. Node n5=new LeafNode(2);
  16.  
  17. Node n6=new LeafNode(9);
  18.  
  19. Node n7=new LeafNode(12);
  20.  
  21. Node n8=new LeafNode(7);
  22.  
  23. Node n9=new LeafNode(8);
  24.  
  25. Node c1=new CompositeNode(n1,n2,n3);
  26.  
  27. Node c4=new CompositeNode(n8,n9);
  28.  
  29. Node c3=new CompositeNode(n5,c4);
  30.  
  31. Node c2=new CompositeNode(n4,c3);
  32.  
  33. Node c5=new CompositeNode(n6,n7);
  34.  
  35. Node root=new CompositeNode(c1,c2,c5);
  36.  
  37. System.out.println(root.getValue());
  38.  
  39. }
  40.  
  41. }
  42.  
  43. abstract class Node{
  44.  
  45. public abstract int getValue();
  46.  
  47. }
  48.  
  49. class LeafNode extends Node{
  50.  
  51. int value;
  52.  
  53. public LeafNode(int value){
  54.  
  55. this.value=value;
  56.  
  57. }
  58.  
  59. public int getValue(){
  60.  
  61. return value;
  62.  
  63. }
  64.  
  65. }
  66.  
  67. class CompositeNode extends Node{
  68.  
  69. private List children=new ArrayList();
  70.  
  71. public CompositeNode(Node... nodes){
  72.  
  73. for(Node n:nodes){
  74.  
  75. children.add(n);
  76.  
  77. }
  78.  
  79. }
  80.  
  81. public int getValue(){
  82.  
  83. int result=0;
  84.  
  85. for(Node n:children){
  86.  
  87. result+=n.getValue();
  88.  
  89. }
  90.  
  91. return result;
  92.  
  93. }
  94.  
  95. }

8.装饰模式(Decorator) 以对客户透明的方式来扩展对象的功能。 用户依据功能需求任意选取组成对象的成分,通过方法的链式调用来实现。 能够给对象动态的添加功能,比继承灵活性更大。

  1. public class TestDecorator {
  2.  
  3. public static void main(String[] args) {
  4.  
  5. Teacher t1=new SimpleTeacher();
  6.  
  7. Teacher t2=new CppTeacher(t1);
  8.  
  9. Teacher t3=new JavaTeacher(t2);
  10.  
  11. t3.teach();
  12.  
  13. //t.teach();
  14.  
  15. }
  16.  
  17. }
  18.  
  19. abstract class Teacher{
  20.  
  21. public abstract void teach();
  22.  
  23. }
  24.  
  25. class SimpleTeacher extends Teacher{
  26.  
  27. public void teach(){
  28.  
  29. System.out.println("Good Good Study, Day Day Up");
  30.  
  31. }
  32.  
  33. }
  34.  
  35. class JavaTeacher extends Teacher{
  36.  
  37. Teacher teacher;
  38.  
  39. public JavaTeacher(Teacher t){
  40.  
  41. this.teacher=t;
  42.  
  43. }
  44.  
  45. public void teach(){
  46.  
  47. teacher.teach();
  48.  
  49. System.out.println("Teach Java");
  50.  
  51. }
  52.  
  53. }
  54.  
  55. class CppTeacher extends Teacher{
  56.  
  57. Teacher teacher;
  58.  
  59. public CppTeacher(Teacher t){
  60.  
  61. this.teacher=t;
  62.  
  63. }
  64.  
  65. public void teach(){
  66.  
  67. teacher.teach();
  68.  
  69. System.out.println("Teach C++");
  70.  
  71. }
  72.  
  73. }

9.代理模式(Proxy) 用一个代理对象来作为还有一个对象的代理,对客户来说是透明的。 存在一个抽象主题类,详细主题类和代理主题类都继承(实现)抽象主题,代理主题类中的方法会调用详细主题类中相相应的方法。

10.享元模式(Flyweight Pattern) 对象的状态分为内蕴状态和外蕴状态。内蕴状态不随环境变化而变化,因此能够作成系统共享.

11.门面模式(Facade) 訪问子系统的时候,通过一个Façade对象訪问。Facade类是单例的。 客户代码仅仅须要和门面对象通信,不须要和详细子系统内部的对象通信,使得他们之间的耦合关系减弱。 这次将表现层和逻辑层隔离,封装底层的复杂处理,为用户提供简单的接口,这种样例随处可见。

门面模式非常多时候更是一种系统架构的设计,在我所做的项目中,就实现了门面模式的接口,为复杂系统的解耦提供了最好的解决方式。

12.桥梁模式(Bridge) 将抽象和实现脱耦,使得二者能够单独变化。使得一个继承关系不承担两个变化因素.使用合成来取代继承的一种体现.

  1. public YuanUser(BankAccount account) {
  2.  
  3. super(account);
  4.  
  5. }
  6.  
  7. public void getMoney() {
  8.  
  9. System.out.print("人民币");
  10.  
  11. account.withdraw();
  12.  
  13. }
  14.  
  15. public void saveMoney() {
  16.  
  17. System.out.print("人民币");
  18.  
  19. account.deposit();
  20.  
  21. }
  22.  
  23. }
  24.  
  25. class DollarUser extends BankUser{
  26.  
  27. public DollarUser(BankAccount account) {
  28.  
  29. super(account);
  30.  
  31. }
  32.  
  33. public void getMoney() {
  34.  
  35. System.out.print("美元");
  36.  
  37. account.withdraw();
  38.  
  39. }
  40.  
  41. public void saveMoney() {
  42.  
  43. System.out.print("美元");
  44.  
  45. account.deposit();
  46.  
  47. }
  48.  
  49. }

行为模式 描写叙述怎样在对象之间划分责任

13.策略模式(Strategy) 如同LayoutManager和详细的布局管理器的关系,在抽象策略类中定义方法,将易于变化的部分封装为接口,通常Strategy 封装一些运算法则,使之能互换。Bruce Zhang在他的博客中提到策略模式事实上是一种“面向接口”的编程方法,真是恰如其分。 在详细策略子类中实现,客户代码依据不同的须要选择对应的详细类,比如电子商务中多种价格算法。 一种策略一旦选中,整个系统执行期是不变化的

  1. public class TestStrategy {
  2.  
  3. public static void main(String[] args) {
  4.  
  5. Strategy s1=new May1Strategy();
  6.  
  7. Strategy s2=new June1Strategy();
  8.  
  9. Book b=new Book(100);
  10.  
  11. b.setS(s2);
  12.  
  13. System.out.println(b.getPrice());
  14.  
  15. }
  16.  
  17. }
  18.  
  19. class Book{
  20.  
  21. Strategy s;
  22.  
  23. public Book(double price){
  24.  
  25. this.price=price;
  26.  
  27. }
  28.  
  29. private double price;
  30.  
  31. public void setS(Strategy s) {
  32.  
  33. this.s = s;
  34.  
  35. }
  36.  
  37. public double getPrice(){
  38.  
  39. return price*s.getZheKou();
  40.  
  41. }
  42.  
  43. }
  44.  
  45. interface Strategy{
  46.  
  47. double getZheKou();
  48.  
  49. }
  50.  
  51. class May1Strategy implements Strategy{
  52.  
  53. public double getZheKou(){
  54.  
  55. return 0.8;
  56.  
  57. }
  58.  
  59. }
  60.  
  61. class June1Strategy implements Strategy{
  62.  
  63. public double getZheKou(){
  64.  
  65. return 0.7;
  66.  
  67. }
  68.  
  69. }

14.模板方法(Template Method) 准备一个抽象类,把部分确定的逻辑定义在某些方法中,用其它抽象方法实现剩余的逻辑。不同子类对这些逻辑有不同的实现。 使用方法:定义多个抽象操作,定义并实现一个模板方法,将步骤放在这个详细方法里,推迟到子类实现。子类能够改变父类的可变部分,但不能改变模板方法所代表的顶级逻辑。

  1. public class TestTemplateMethod {
  2.  
  3. public static void main(String[] args) {
  4.  
  5. XiaoPin xp=new DaPuKe();
  6.  
  7. xp.act();
  8.  
  9. }
  10.  
  11. }
  12.  
  13. abstract class XiaoPin{
  14.  
  15. public abstract void jiaoLiu();
  16.  
  17. public abstract void xuShi();
  18.  
  19. public abstract void gaoXiao();
  20.  
  21. public abstract void shanQing();
  22.  
  23. public final void act(){
  24.  
  25. jiaoLiu();
  26.  
  27. xuShi();
  28.  
  29. gaoXiao();
  30.  
  31. shanQing();
  32.  
  33. }
  34.  
  35. }
  36.  
  37. class DaPuKe extends XiaoPin{
  38.  
  39. public void jiaoLiu(){
  40.  
  41. System.out.println("顺口溜");
  42.  
  43. }
  44.  
  45. public void xuShi(){
  46.  
  47. System.out.println("火车除夕,老同学见面");
  48.  
  49. }
  50.  
  51. public void gaoXiao(){
  52.  
  53. System.out.println("名片当作扑克");
  54.  
  55. }
  56.  
  57. public void shanQing(){
  58.  
  59. System.out.println("马家军");
  60.  
  61. }
  62.  
  63. }

15.观察者模式(Observer) 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时, 全部依赖于它的对象都得到通知并被自己主动更新。观察者和被观察者的分开,为模块划分提供了清晰的界限。在低耦合的对象间完毕协调。 Java中的事件模型就是一个应用。

16.迭代器模式(Iterator) 相似于集合中的Iterator,使用迭代器来统一不同集合对象的遍历方式。在绝大多数的系统中,都会用到数组、集合、链表、队列这种类型,关心迭代模式的来龙去脉很有必要。在遍历算法中,迭代模式提供了遍历的顺序訪问容 器,GOF给出的定义为:提供一种方法訪问一个容器(container)对象中各个元素,而又不需暴露该对象的内部细节。.NET中就是使用了迭代器来 创建用于foreach的集合。

  1. public class TestIterator {
  2.  
  3. public static void main(String[] args) {
  4.  
  5. Stack s=new Stack();
  6.  
  7. s.push("Liucy");
  8.  
  9. s.push("Huxz");
  10.  
  11. s.push("George");
  12.  
  13. LinkedList l=new LinkedList();
  14.  
  15. l.addFirst("Liucy");
  16.  
  17. l.addFirst("Huxz");
  18.  
  19. l.addFirst("George");
  20.  
  21. print(l.iterator());
  22.  
  23. }
  24.  
  25. public static void print(Itr it){
  26.  
  27. while(it.hasNext()){
  28.  
  29. System.out.println(it.next());
  30.  
  31. }
  32.  
  33. }
  34.  
  35. }
  36.  
  37. interface Itr{
  38.  
  39. boolean hasNext();
  40.  
  41. Object next();
  42.  
  43. }
  44.  
  45. class Stack{
  46.  
  47. Object[] os=new Object[10];
  48.  
  49. int index=0;
  50.  
  51. private void expand(){
  52.  
  53. Object[] os2=new Object[os.length*2];
  54.  
  55. System.arraycopy(os,0,os2,0,os.length);
  56.  
  57. os=os2;
  58.  
  59. }
  60.  
  61. public void push(Object o){
  62.  
  63. if (index==os.length) expand();
  64.  
  65. os[index]=o;
  66.  
  67. index++;
  68.  
  69. }
  70.  
  71. public Object pop(){
  72.  
  73. index--;
  74.  
  75. Object o=os[index];
  76.  
  77. os[index]=null;
  78.  
  79. return o;
  80.  
  81. }
  82.  
  83. private class StackItr implements Itr{
  84.  
  85. int cursor=0;
  86.  
  87. public boolean hasNext(){
  88.  
  89. return cursor}
  90.  
  91. public Object next(){
  92.  
  93. return os[cursor++];
  94.  
  95. }
  96.  
  97. }
  98.  
  99. public Itr iterator(){
  100.  
  101. return new StackItr();
  102.  
  103. }
  104.  
  105. }
  106.  
  107. class LinkedList{
  108.  
  109. private class Node{
  110.  
  111. Object o;
  112.  
  113. Node next;
  114.  
  115. public Node(Object o){
  116.  
  117. this.o=o;
  118.  
  119. }
  120.  
  121. public void setNext(Node next){
  122.  
  123. this.next=next;
  124.  
  125. }
  126.  
  127. public Node getNext(){
  128.  
  129. return this.next;
  130.  
  131. }
  132.  
  133. }
  134.  
  135. Node head;
  136.  
  137. public void addFirst(Object o){
  138.  
  139. Node n=new Node(o);
  140.  
  141. n.setNext(head);
  142.  
  143. head=n;
  144.  
  145. }
  146.  
  147. public Object removeFirst(){
  148.  
  149. Node n=head;
  150.  
  151. head=head.getNext();
  152.  
  153. return n.o;
  154.  
  155. }
  156.  
  157. class LinkedListItr implements Itr{
  158.  
  159. Node currentNode=head;
  160.  
  161. public boolean hasNext(){
  162.  
  163. return this.currentNode!=null;
  164.  
  165. }
  166.  
  167. public Object next(){
  168.  
  169. Node n=currentNode;
  170.  
  171. currentNode=currentNode.getNext();
  172.  
  173. return n.o;
  174.  
  175. }
  176.  
  177. }
  178.  
  179. public Itr iterator(){
  180.  
  181. return new LinkedListItr();
  182.  
  183. }
  184.  
  185. }

17.责任链(Chain of Responsibility) 多个处理器对象连成一串,请求在这条链上传递,由该处理这个请求的处理器来处理。发出请求的client并不知道哪个对象处理请求。

  1. public class TestChain {
  2.  
  3. public static void main(String[] args) {
  4.  
  5. String pass1="123456";
  6.  
  7. String pass2="123456";
  8.  
  9. String personId="123456789012345678";
  10.  
  11. String email="chmask@163.com";
  12.  
  13. register(pass1,pass2,personId,email);
  14.  
  15. }
  16.  
  17. public static void register(String pass1,String pass2,String personId,String email){
  18.  
  19. Filter f1=new PasswordFilter1();
  20.  
  21. Filter f2=new PasswordFilter2();
  22.  
  23. Filter f3=new PersonIdFilter();
  24.  
  25. Filter f4=new EmailFilter();
  26.  
  27. f1.setNext(f2);
  28.  
  29. f2.setNext(f3);
  30.  
  31. f3.setNext(f4);
  32.  
  33. System.out.println(f1.doFilter(pass1,pass2,personId,email));
  34.  
  35. }
  36.  
  37. }
  38.  
  39. abstract class Filter{
  40.  
  41. Filter next=null;
  42.  
  43. public Filter getNext() {
  44.  
  45. return next;
  46.  
  47. }
  48.  
  49. public void setNext(Filter next) {
  50.  
  51. this.next = next;
  52.  
  53. }
  54.  
  55. public String doFilter(String pass1,String pass2,String personId,String email){
  56.  
  57. if (next==null) return "成功";
  58.  
  59. else return next.doFilter(pass1,pass2,personId,email);
  60.  
  61. }
  62.  
  63. }
  64.  
  65. class PasswordFilter1 extends Filter{
  66.  
  67. public String doFilter(String pass1,String pass2,String personId,String email){
  68.  
  69. if (!(pass1.equals(pass2)))
  70.  
  71. return "两次password输入不一致";
  72.  
  73. else return super.doFilter(pass1,pass2,personId,email);
  74.  
  75. }
  76.  
  77. }
  78.  
  79. class PasswordFilter2 extends Filter{
  80.  
  81. public String doFilter(String pass1,String pass2,String personId,String email){
  82.  
  83. if (pass1.length()!=6)
  84.  
  85. return "password长度必须为6";
  86.  
  87. else return super.doFilter(pass1,pass2,personId,email);
  88.  
  89. }
  90.  
  91. }
  92.  
  93. class PersonIdFilter extends Filter{
  94.  
  95. public String doFilter(String pass1,String pass2,String personId,String email){
  96.  
  97. if (personId.length()!=15 && personId.length()!=18)
  98.  
  99. return "身份证号码非法";
  100.  
  101. else return super.doFilter(pass1,pass2,personId,email);
  102.  
  103. }
  104.  
  105. }
  106.  
  107. class EmailFilter extends Filter{
  108.  
  109. public String doFilter(String pass1,String pass2,String personId,String email){
  110.  
  111. int i1=email.indexOf("@");
  112.  
  113. int i2=email.indexOf(".");
  114.  
  115. if (i1==-1 || i2==-1 || i2-i1<=1 || i1==0 || i2==email.length()-1)
  116.  
  117. return "email非法";
  118.  
  119. else return super.doFilter(pass1,pass2,personId,email);
  120.  
  121. }
  122.  
  123. }

18.状态模式(State) 在对象内部状态改变时改变其行为。把所研究的对象的行为封装在不同的状态对象中。

  1. import static java.lang.System.*;
  2.  
  3. public class TestState {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. BBSUser u=new BBSUser();
  8.  
  9. u.setState(new GuestState());
  10.  
  11. u.publish();
  12.  
  13. u.setState(new NormalState());
  14.  
  15. u.publish();
  16.  
  17. u.setState(new BlockedState());
  18.  
  19. u.publish();
  20.  
  21. u.setState(new NewComerState());
  22.  
  23. u.publish();
  24.  
  25. }
  26.  
  27. }
  28.  
  29. class BBSUser{
  30.  
  31. private State state;
  32.  
  33. public void setState(State state){
  34.  
  35. this.state=state;
  36.  
  37. }
  38.  
  39. public void publish(){
  40.  
  41. state.action();
  42.  
  43. }
  44.  
  45. }
  46.  
  47. abstract class State{
  48.  
  49. public abstract void action();
  50.  
  51. }
  52.  
  53. class GuestState extends State{
  54.  
  55. public void action(){
  56.  
  57. out.println("您处在游客状态,请先登录");
  58.  
  59. }
  60.  
  61. }
  62.  
  63. class NormalState extends State{
  64.  
  65. public void action(){
  66.  
  67. out.println("您处在正常状态,文章发表成功");
  68.  
  69. }
  70.  
  71. }
  72.  
  73. class BlockedState extends State{
  74.  
  75. public void action(){
  76.  
  77. out.println("您处在被封状态,文章发表失败");
  78.  
  79. }
  80.  
  81. }
  82.  
  83. class NewComerState extends State{
  84.  
  85. public void action(){
  86.  
  87. out.println("您是新手,请先学习一下,3天后再来");
  88.  
  89. }
  90.  
  91. }
  92.  
  93. class StateFactory{
  94.  
  95. public static State createState(int i){
  96.  
  97. if (i==1) return new GuestState();
  98.  
  99. else return new NormalState();
  100.  
  101. }
  102.  
  103. }

19.备忘录模式(Memento) 备忘录对象用来存储还有一个对象的快照对象,保存其内部状态,使得能够随时恢复。 备忘录角色:保存发起人对象的内部状态,保护内容不被除发起人对象之外的对象获取。窄接口:负责人对象和其它对象看到的接口,仅仅同意把备忘录对象传给其它对象。宽接口:发起人能看到的接口,同意读取内部状态。 发起人角色:创建并使用备忘录对象来保存其状态 负责人角色:负责保存备忘录对象。  白箱实现:备忘录类对其它类也可见,这样发起人的状态可能会存在安全问题。  黑箱实现:把备忘录类作成发起人的内部类,对外提供一个标识接口。

  1. public class TestMemento{
  2.  
  3. public static void main(String[] args){
  4.  
  5. Originator ori=new Originator();
  6.  
  7. Caretaker c=new Caretaker();
  8.  
  9. ori.setState("State 1");
  10.  
  11. IFMemento m=ori.createMemento();
  12.  
  13. c.save(m);
  14.  
  15. ori.setState("State 2");
  16.  
  17. m=c.retrieve();
  18.  
  19. ori.restore(m);
  20.  
  21. System.out.println("Now State:"+ori.getState());
  22.  
  23. }
  24.  
  25. }
  26.  
  27. class Originator{
  28.  
  29. String state;
  30.  
  31. public void setState(String s){
  32.  
  33. state=s;
  34.  
  35. System.out.println("State change to: "+s);
  36.  
  37. }
  38.  
  39. public String getState(){
  40.  
  41. return this.state;
  42.  
  43. }
  44.  
  45. public IFMemento createMemento(){
  46.  
  47. return new Memento(state);
  48.  
  49. }
  50.  
  51. public void restore(IFMemento m){
  52.  
  53. Memento mt=(Memento)m;
  54.  
  55. this.state=mt.getState();
  56.  
  57. }
  58.  
  59. private class Memento implements IFMemento{
  60.  
  61. private String state;
  62.  
  63. public Memento(String s){
  64.  
  65. this.state=s;
  66.  
  67. }
  68.  
  69. public String getState(){
  70.  
  71. return this.state;
  72.  
  73. }
  74.  
  75. }
  76.  
  77. }
  78.  
  79. class Caretaker{
  80.  
  81. private IFMemento m;
  82.  
  83. public IFMemento retrieve(){
  84.  
  85. return this.m;
  86.  
  87. }
  88.  
  89. public void save(IFMemento m){
  90.  
  91. this.m=m;
  92.  
  93. }
  94.  
  95. }
  96.  
  97. interface IFMemento{
  98.  
  99. }

java设计模式演示样例的更多相关文章

  1. Java线程演示样例 - 继承Thread类和实现Runnable接口

    进程(Process)和线程(Thread)是程序执行的两个基本单元. Java并发编程很多其它的是和线程相关. 进程 进程是一个独立的执行单元,可将其视为一个程序或应用.然而,一个程序内部同事还包括 ...

  2. Java多线程演示样例(模拟通话,sleep,join,yield,wait,notify,Semaphore)

    主线程等待子线程的多种方法 synchronized浅析 sleep 是静态方法,Thread.sleep(xx)谁调用谁睡眠. join 是合并方法.当前线程调用其它线程xx.join()则等到xx ...

  3. java监听器演示样例

    监听器的原理是观察者模式.就像明星(事件源)聚拢了一群粉丝(观察者).当明星有啥举动的时候会通过粉丝们报道出去. 订阅信息.计算器button都是该原理的应用. 以下写了一个监听器的小样例: pack ...

  4. HTTP基本认证(Basic Authentication)的JAVA演示样例

    大家在登录站点的时候.大部分时候是通过一个表单提交登录信息.可是有时候浏览器会弹出一个登录验证的对话框.例如以下图,这就是使用HTTP基本认证.以下来看看一看这个认证的工作过程:第一步:  clien ...

  5. Java 8 时间日期库的20个使用演示样例

    除了lambda表达式,stream以及几个小的改进之外,Java 8还引入了一套全新的时间日期API,在本篇教程中我们将通过几个简单的任务演示样例来学习怎样使用Java 8的这套API.Java对日 ...

  6. java文件夹相关操作 演示样例代码

    java文件夹相关操作 演示样例代码 package org.rui.io; import java.io.File; import java.io.FilenameFilter; import ja ...

  7. java 覆盖hashCode()深入探讨 代码演示样例

    java 翻盖hashCode()深入探讨 代码演示样例 package org.rui.collection2.hashcode; /** * 覆盖hashcode * 设计HashCode时最重要 ...

  8. java并行调度框架封装及演示样例

    參考资料:  阿里巴巴开源项目 CobarClient  源代码实现. 分享作者:闫建忠 分享时间:2014年5月7日 ---------------------------------------- ...

  9. Java连接redis的使用演示样例

    Java连接redis的使用演示样例 Redis是开源的key-value存储工具,redis通经常使用来存储结构化的数据,由于redis的key能够包括String.hash.listset和sor ...

随机推荐

  1. SGU 172.eXam(二分图染色)

    时间限制:0.25s 空间限制:4M 题意: 将n(n<200)个点分成两个集合,给出m(m<=30000)对不能在一个集合的点对,判断能否分成满足要求的集合,输出其中一个集合和集合的总数 ...

  2. 3 - testng.xml

    TestNG的调用有以下几种方式: testng.xml ant 命令行 这部分主要介绍testng.xml的格式. 当前testng.xml的DTD(文档类型定义(Document Type Def ...

  3. Jquery 获取日期date()对象

    获取JavaScript 的时间使用内置的Date函数完成 var mydate = new Date(); mydate.getYear(); //获取当前年份(2位) mydate.getFull ...

  4. web版扫雷小游戏(二)

    接上篇~~第一次写这种技术博客,发现把自己做的东西介绍出来还是一件脑力活,不是那么轻松啊,好吧,想到哪写到哪,流水记录之,待完成之后再根据大家的意见进行修改吧. 游戏实现 根据对扫雷游戏的体验和分析, ...

  5. C# 当double数值较大且小数位过多时转化成字符串并保留小数位

    今天在C#中碰到了一个问题,需要将double转换成字符串显示,要求保留小数位. 在网上查询了一下相关的文章 具体如下: double temp=3.1415926; (F)Fixed point:s ...

  6. How do I solve the error: An error was encountered while running (Domain = LaunchServicesError, Code = 0) ?

    How do I solve the error: An error was encountered while running (Domain = LaunchServicesError, Code ...

  7. Mongodb2.6升级到Mongodb3.0.2笔记

    PS:升级到3版本的Mongodb以后,drop集合是可以直接释放磁盘空间的 停止老版本Mongodb >use admin >db.shutdownServer(); 下载解压新版本Mo ...

  8. 简述MVC思想 与PHP如何实现MVC

    我相信已经有很多这样的文章了,但是我今天还是愿意把自己的经验与大家分享一下.纯属原创,我也没什么保留,希望对新手有帮助,有说的不对的地方,也欢迎指出. 什么是MVC? 简单的说就是将网站源码分类.分层 ...

  9. Node.js Express框架

    Express 介绍 Express是一个最小的,灵活的Node.js Web应用程序框架,它提供了一套强大的功能来开发Web和移动应用程序. 它有助于基于Node Web应用程序的快速开发.下面是一 ...

  10. 查看SharePoint list的xml

    http://{0}/_vti_bin/owssvr.dll?Cmd=Display&List={1}&XMLDATA=TRUE {0} – The URL to your site. ...