用意:通过给出一个原型对象来指明所要创建的对象的类型,然后用复制这个原型对象的办法创建出更多同类型的对象。

1. com.cleversoft.designpatterns.prototype.Prototype.java:

package  com.cleversoft.designpatterns.prototype;

interface  Prototype  {
    Object clone();

    String getName();

    
void  execute();
}

2. com.cleversoft.designpatterns.prototype.This.java:
package com.cleversoft.designpatterns.prototype;

class This implements Prototype {
    
public Object clone() {
        
return new This();
    }


    
public String getName() {
        
return "This";
    }


    
public void execute() {
        System.out.println(
"This: execute");
    }

}

3. com.cleversoft.designpatterns.prototype.That.java:
package com.cleversoft.designpatterns.prototype;

class That implements Prototype {
    
public Object clone() {
        
return new That();
    }


    
public String getName() {
        
return "That";
    }


    
public void execute() {
        System.out.println(
"That: execute");
    }

}

4. com.cleversoft.designpatterns.prototype.PrototypesModule.java:
package com.cleversoft.designpatterns.prototype;

class PrototypesModule {
    
private static Prototype[] prototypes = new Prototype[9];

    
private static int total = 0;

    
public static void addPrototype(Prototype obj) {
        prototypes[total
++= obj;
    }


    
public static Object findAndClone(String name) {
        
for (int i = 0; i < total; i++)
            
if (prototypes[i].getName().equals(name))
                
return prototypes[i].clone();
        System.out.println(name 
+ " not found");
        
return null;
    }

}

5. com.cleversoft.designpatterns.prototype.Main.java:
package com.cleversoft.designpatterns.prototype;

public class Main {
    
public static void initializePrototypes() {
        PrototypesModule.addPrototype(
new This());
        PrototypesModule.addPrototype(
new That());
    }


    
public static void main(String[] args) {
        initializePrototypes();
        Object[] objects 
= new Object[9];
        
int total = 0;

        
for (int i = 0; i < args.length; i++{
            objects[total] 
= PrototypesModule.findAndClone(args[i]);
            
if (objects[total] != null)
                total
++;
        }

        
for (int i = 0; i < total; i++)
            ((Prototype) objects[i]).execute();

    }

}


参考资料:
1. 《Java与模式》
2. http://terrylee.cnblogs.com/archive/2006/01/16/317896.html
3. Design Patterns With Code
4. Thinking in Patterns

欢迎大家访问我的个人网站 萌萌的IT人