创建一个模式

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 设计模式(示例代码)

    Java 设计模式 项目实例:https://github.com/windwant/java-design-pattern

  2. java设计模式演示样例

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

  3. 一个简单的java僵局演示示例

    在实际编程,为了避免死锁情况,但是,让你写一个有用的程序死锁似几乎不要太简单(种面试题),下面是一个简单的死锁样例. 线程的同步化可能会造成死锁,死锁发生在两个线程相互持有对方正在等待的东西(实际是两 ...

  4. java 添加一个线程、创建响应的用户界面 。 演示示例代码

    javajava 添加一个线程.创建响应的用户界面 . 演示示例代码 来自thinking in java 4 21章  部分的代码  夹21.2.11 thinking in java 4免费下载: ...

  5. Java 设计模式 -- 示例指南

    设计模式在软件开发者中非常受欢迎的.每个设计模式都是对常见软件问题的通用的描述解决方案. 我们使用设计模式的好处有: 1.设计模式已经对于一个重复出现的问题进行了定义并且提供了工业标准的解决方案,因为 ...

  6. JAVA设计模式-动态代理(Proxy)示例及说明

    在Mybatis源码解析,一步一步从浅入深(五):mapper节点的解析文章的最后部分,我们提到了动态代理的概念,下面我们就简单了解一下动态代理. 一,概念 代理设计模式的目的就是在不直接操作对象的前 ...

  7. Java设计模式(22)命令模式(Command模式)

    Command模式是最让我疑惑的一个模式,我在阅读了很多代码后,才感觉隐约掌握其大概原理,我认为理解设计模式最主要是掌握起原理构造,这样才对自己实际编程有指导作用.Command模式实际上不是个很具体 ...

  8. Java设计模式学习笔记(一) 设计模式概述

    前言 大约在一年前学习过一段时间的设计模式,但是当时自己的学习方式比较低效,也没有深刻的去理解.运用所学的知识. 所以现在准备系统的再重新学习一遍,写一个关于设计模式的系列博客. 废话不多说,正文开始 ...

  9. JAVA设计模式-单例模式(Singleton)线程安全与效率

    一,前言 单例模式详细大家都已经非常熟悉了,在文章单例模式的八种写法比较中,对单例模式的概念以及使用场景都做了很不错的说明.请在阅读本文之前,阅读一下这篇文章,因为本文就是按照这篇文章中的八种单例模式 ...

随机推荐

  1. python 入门学习---模块导入三种方式及中文凝视

    Python 有三种模块导入函数 1. 使用import 导入模块 import modname : 模块是指一个能够交互使用,或者从还有一Python 程序訪问的代码段.仅仅要导入了一个模块,就能够 ...

  2. ZOJ 3635 Cinema in Akiba(线段树)

    Cinema in Akiba (CIA) is a small but very popular cinema in Akihabara. Every night the cinema is ful ...

  3. 正则匹配去掉字符串中的html标签

    1.得到超链接中的链接地址: string matchString = @"<a[^>]+href=\s*(?:'(?<href>[^']+)'|"&quo ...

  4. Python 类继承,__bases__, __mro__, super

    Python是面向对象的编程语言,也支持类继承. >>> class Base: ... pass ... >>> class Derived(Base): ... ...

  5. JqGrid 显示表

    JqGrid 下表显示了前台图书馆.使用起来非常方便. 我在这里分享使用中遇到的问题及解决方案 ** 一.rowNum属性 ** 1.假设不设置,默认显示数是20,也就是说超过20以后的数据.不再显示 ...

  6. My Solution: Word Ladder

    public class Solution { public int ladderLength(String start, String end, Set<String> dict) { ...

  7. async和await用法

    原文:async和await用法 要理解async和await的用法,首先要了解Task相关知识,这里不做说明,因为这不是本文的重点. 如果你已经对Task很了解,那么如何使用async和await, ...

  8. ViewPager.getChildCount() 含义

    viewpager.getChildCount() 非常easy误解成viewpager子页面的size.它和getCount还是有差别的 getChildCount() 是表示当前可见页size 比 ...

  9. oracle 转 mysql 最新有效法(转)

    关键字:Oracle 转 MySQL . Oracle TO MySQL 没事试用了一下Navicat家族的新产品Navicat Premium,他集 Oracle.MySQL和PostgreSQL管 ...

  10. listary文件查找程序下载和使用

    资源:PHP开发学习门户网站 地址:http://bbs.phpthinking.com/forum.php?mod=viewthread&tid=173 Listary 是一款有用的国产Wi ...