Get the App
SLTechnology News&Howtos  ›  Network Security  › 

Design pattern-Agent pattern

Shulou Source: shulou.com Published: 2022-06-01 02:47:39 10月04日 Update

Agent mode: the agent and the principal realize the common behavior, and then let the agent system call the principal to complete these behaviors.

Example: the agent Proxy acts on behalf of MrLi to send gifts to MrssHong.

The class diagram is as follows:

Code implementation:

Define an interface for giving gifts: GiveGift

Package com.zpj.designMode.proxy;// defines an interface for giving gifts: public interface GiveGift {public void giveFlowers (); public void giveDolls (); public void giveChocolate ();}

Implement MrLi:

Package com.zpj.designMode.proxy;/** * MrLi will chase girls to give gifts, so to implement the interface GiveGift * / public class MrLi implements GiveGift {private MrssHong hong;// is pursued by public MrLi (MrssHong hong) {this.hong = hong;} @ Override public void giveFlowers () {System.out.println ("- send flowers -" + hong.getName ()) } @ Override public void giveDolls () {System.out.println ("- send dolls -" + hong.getName ();} @ Override public void giveChocolate () {System.out.println ("- send chocolates -" + hong.getName ());}}

Implement the proxy Proxy:

Package com.zpj.designMode.proxy;public class Proxy implements GiveGift {private MrLi person;// principal public Proxy (MrssHong hong) {person = new MrLi (hong);} @ Override public void giveFlowers () {person.giveFlowers ();} @ Override public void giveDolls () {person.giveDolls ();} @ Override public void giveChocolate () {person.giveChocolate ();}

Gift recipient: MrssHong

Package com.zpj.designMode.proxy;public class MrssHong {private String name; public MrssHong (String name) {super (); this.name = name;} public String getName () {return name;} public void setName (String name) {this.name = name;}}

Test class:

Package com.zpj.designMode.proxy;import org.junit.Test;public class TestUnit {@ Test public void test01 () {MrssHong hong = new MrssHong ("Red × × ×"); / / tell the agent who to send the gift, this agent belongs exclusively to MrLi Proxy proxy = new Proxy (hong); / / the agent sends the gift proxy.giveFlowers (); proxy.giveChocolate (); proxy.giveDolls () }}

Tags: Agents interfaces behaviors patterns agents codes girls chocolates dolls examples principals flowers testing design patterns design Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Apple Shulou Tech Info MySQL Docker