设计模式之代理模式

售票处的抽象接口(抽象主题角色)

/**
 * @Author: chuan.bai
 * @Description 售票处
 * @Date: Created on 14:56 2021/3/24
 * @Modified By:
 */
public interface Ticketing {

    /**
     * 买火车票抽象类
     */
    void buyTicket();
}

火车站售票处(真实主题角色)

/**
 * @Author: chuan.bai
 * @Description 火车站售票处
 * @Date: Created on 15:10 2021/3/24
 * @Modified By:
 */
public class RailwayStationTicket implements Ticketing{

    private String tickName;

    public RailwayStationTicket(String tickName) {
        this.tickName=tickName;
    }

    @Override
    public void buyTicket() {
        System.out.println("买到火车票:"+tickName);
    }
    
}

火车票的代理售票处(代理主题角色)

/**
 * @Author: chuan.bai
 * @Description 代理售票处
 * @Date: Created on 15:14 2021/3/24
 * @Modified By:
 */
public class ProxyTicket implements Ticketing{

    private RailwayStationTicket railwayStationTicket;

    private String tickName;

    public ProxyTicket(String tickName) {
        this.tickName = tickName;
    }

    @Override
    public void buyTicket() {
        System.out.println("进入了代理售票处");
        RailwayStationTicket railwayStationTicket = new RailwayStationTicket(tickName);
        railwayStationTicket.buyTicket();
    }
}

用户

/**
 * @Author: chuan.bai
 * @Description
 * @Date: Created on 15:26 2021/3/24
 * @Modified By:
 */
public class Customer {

    public static void main(String[] args) {
        Ticketing ticketing =new ProxyTicket("A12345");
        ticketing.buyTicket();
    }
}

最后输出结果为

进入了代理售票处
买到火车票:A12345

你可能感兴趣的:(设计模式之代理模式)