Command Pattern Create a class to save the class instance (command.class) and treat the method of the saved class instance like the command.class method.
On this page -Simple Command pattern -Addition of a function to display the number of method executions I will describe about
It has the following configuration
class | Explanation |
---|---|
command.interface | Make the registered instance common |
samCommand1.class | Implement command and have one method |
samCommand2.class | Implement command and have one method |
commandPool.class | Save instances of samCommand1 and samCommand2 |
user(Main.class) | Command.Check the operation of class |
command.interface
interface command{
void s();
}
samCommand1.class
class samCommand1 implements command{
public void s(){System.out.println("command1");}
}
samCommand2.class
class samCommand2 implements command{
public void s(){System.out.println("command2");}
}
commandPool.class
class commandPool{
command[] pool=new command[2]; // command.Stores a class instance that implements interface
void set(int key,command com){
if(pool[key]==null){
pool[key]=com;
}
}
void exec(int key){
pool[key].s();
}
}
user(Main.class)
public static void main(String[] args){
samCommand1 sc1 = new samCommand1();
samCommand2 sc2 = new samCommand2();
commandPool cop = new commandPool();
cop.set(0,sc1);
cop.set(1,sc2);
cop.exec(1);
}}
Modify commandPool.class to below
commandPool.class
class commandPool{
command[] pool = new command[4];
int[] count = new int[2];
void set(int key,command com){
if(pool [key]==null){
pool [key]=com;
count[key]=0;
}
}
void exec(int key){
pool [key].s();
count[key]++;
System.out.println(count[key]+"Time");
}
}
Recommended Posts