Prototype Pattern Copy and use the instance
On this page ・ Confirmation of Prototype Pattern -Store and use the instance in the Map collection I will describe about
Check with the following class structure
class | Explanation |
---|---|
samPrototype.class | Have a method to make a copy of yourself |
user(Main.class) | Check the operation |
If you use the clone () method, implement the java.lang.Cloneable interface
Let's check
samPrototype.class
class samPrototype implements Cloneable{ // java.lang.Implement Cloneable
void todo(){System.out.println("prototype");}
samPrototype getClone(){
samPrototype pro = null;
try{pro=(samPrototype) clone(); // clone()And make a copy of itself
}catch(Exception e){}
return pro;
}
}
user(Main.class)
public static void main(String[] args){
samPrototype pr = new samPrototype();
pr.getClone().todo();
}}
For Prototype Pattern, register multiple instances in advance There is a usage to execute clone () if necessary
Implement with the following configuration
name of the class | Explanation |
---|---|
prototype.interface | Implement Cloneable and clone()Define a method |
prototypeImple.class | prototype.Implement interface and clone()Implement the method |
prototypeManager.class | Keep a class instance that implements prototype in a collection clone in prototype type()Issue an instance using a method |
user(Main.class) | Check the operation |
Let's make a class
prototype.interface
interface prototype extends Cloneable{
void todo();
prototype exeClone();
}
prototypeImple.class
class prototypeImple implements prototype{
String name;
prototypeImple(String name){this.name=name;}
public void todo(){System.out.println(name);}
public prototype exeClone(){
prototype pro = null;
try{pro = (prototype) clone();}catch(Exception e){}
return pro;
}
}
usr(Main.class)
public static void main(String[] args){
prototypeManager pm = new prototypeManager();
pm.set(0, new prototypeImple("A"));
pm.set(1, new prototypeImple("B"));
prototype p1 = pm.getClone(0);
prototype p2 = pm.getClone(1);
p1.todo();
p2.todo();
}}
Recommended Posts