Create a Leader class (delegate)
package delegate; import java.util.HashMap; import java.util.Map; public class Leader { private Map<String, ICode> coder = new HashMap<>(); public Leader() { coder.put("A", new CoderA()); coder.put("B", new CoderB()); } public void dispatch(String target) { coder.get(target).coding(target); }}Copy the code
2. Create an interface
package delegate;
public interface ICode {
void coding(String task);
}
Copy the code
3. Two coder classes
package delegate; Public implements ICode {@override public void coding(String task) {system.out.println (" implements function "+ task); }}Copy the code
package delegate; Public class implements ICode {@override public void coding(String task) {system.out.println (" implements function "+ task); }}Copy the code
4. Test (entrust the task to the consignor, and the consignor assigns the task to the implementer)
package delegate; public class DelegateTest { public static void main(String[] args) { Leader leader = new Leader(); leader.dispatch("A"); leader.dispatch("B"); }}Copy the code