java Design Patterns ------ strategy mode

A concept

Simply put, the strategy pattern is to deal with the rule changes and new rules added influence on the program brings. For object-oriented programming how to achieve it? Avoid calling rules directly through the interface, so that the change will not have an impact on business rules. At the same time, add a new rule will not affect the business processes.

Strategy Mode three roles:

  ● Environment (Context) role: to hold a Strategy of reference, so any particular class only need to implement the policy environment interface can be passed in the role, so that each specific policy environment will be a new role as a carrier strategy to implement different strategies .

  ● abstract strategy (Strategy) Role: This is an abstract role, usually implemented by an interface or abstract class. This role gives specific strategies required for all class interface.

  ● specific strategies (ConcreteStrategy) role: the role of inheritance or implement abstract strategy, packaging related algorithms or behavior.

II. Code three roles tender strategy mode

1. environmental role

public class Context {
    //持有一个具体策略的对象
    private Strategy strategy;
    /**
     * 构造函数,传入一个具体策略对象
     * @param strategy    具体策略对象
     */
    public Context(Strategy strategy){
        this.strategy = strategy;
    }
    /**
     * 策略方法
     */
    public void contextInterface(){
        
        strategy.strategyInterface();
    }
    
}

2. abstract strategy interface class


public interface Strategy {
    /**
     * 策略方法
     */
    public void strategyInterface();
}

3. A concrete strategy class

public class ConcreteStrategyA implements Strategy {
 
    @Override
    public void strategyInterface() {
        //相关的业务
    }
 
}

4. DETAILED Strategy B

public class ConcreteStrategyB implements Strategy {
 
    @Override
    public void strategyInterface() {
        //相关的业务
    }
 
}

5. Test Class

public class TestStratege {

     public static void main (String[] args) {
         
         ConcreteStrategyA  concreteStrategyA  = new ConcreteStrategyA();
         Context contextA = new Context (concreteStrategyA);
         contextA .contextInterface();

         ConcreteStrategyB  concreteStrategyB  = new ConcreteStrategyB();
         Context contextB = new Context (concreteStrategyB);
         contextB .contextInterface();

     }
}

III. Combat scenarios

  Necessary to manufacture a number of existing parking, outpatient, visitors, hotel data, need to go through data acquisition, package, pushed rabbitmq of three processes.

1. Environmental role prepared (as a thread class, each data type corresponds to one thread environment)


public class DispatchThread<T> implements Runnable {
    private DataHandle<T> dataHandle;
    private RabbitMqParams params;

    public DispatchThread(DataHandle<T> dataHandle, RabbitMqParams params){
        this.dataHandle=dataHandle;
        this.params=params;
    }
    @Override
    public void run() {
        T t;
        while (true){
            try {
                t= dataHandle.getData();
                t = dataHandle.format(t);
                dataHandle.sendData(params,t);
                Thread.sleep(20*1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}

2. Strategy ---- abstract strategy interfaces (providing access to data, packaging data and push data interface templates)


public interface DataHandle<T> {
    T getData();
    T format(T t);
    void sendData(RabbitMqParams params,T t);
}

3. Specific Strategy Implementation Strategy ---- Interface

(1) Parking Strategy Implementation Strategy --- Interface


public class PicParkDataHandle implements DataHandle<PicPark> {
    private static final Logger logger = Logger.getLogger(PicParkDataHandle.class);
    @Override
    public PicPark getData() {
        String json = "xxxxx";
        PicPark picPark = JSON.parseObject(json, PicPark.class);
        return picPark;
    }

    @Override
    public PicPark format(PicPark picPark) {
        picPark.setAreaName(picPark.getAreaName()+System.currentTimeMillis());
        picPark.setCapTime(System.currentTimeMillis());
        picPark.setCreateTime(System.currentTimeMillis());
        picPark.setObjId(RandomPlateUtil.generateCarID());
        picPark.setPlateNum(picPark.getObjId());
        picPark.setRecordId(UUID.randomUUID().toString().replace("-",""));
        return picPark;
    }

    @Override
    public void sendData(RabbitMqParams params,PicPark picPark) {
        RabbitProductClient client=new RabbitProductClient(params.getExchangName(),params.getHost(),params.getPort(),params.getUsername(),params.getPassword(),params.getExchangeType());
        try {
            client.sendMessage(JSON.toJSONString(picPark),params.getRouteKey());
            logger.info("停车场数据发送成功: " + JSON.toJSONString(picPark));
        } catch (Exception e) {
            logger.error("发送停车场数据出错");
            e.printStackTrace();
        }
    }
}

(2) ----- class hotel policy implementation strategies Interface


public class HotelHandle implements DataHandle<Hotel> {
    private static final Logger logger = Logger.getLogger(HotelHandle.class);
    @Override
    public Hotel getData() {
        Hotel hotel=new Hotel();
        hotel.setBirthday("1995-10-20");
        hotel.setCapTime(System.currentTimeMillis());
        hotel.setCardNo(IdCardGenerator.generate());
        hotel.setCreateTime(System.currentTimeMillis());
        hotel.setInTime(System.currentTimeMillis());
        hotel.setLeaveTime(System.currentTimeMillis());
        hotel.setName(NameGenerator.build());
        hotel.setNation("汉族");
        hotel.setNativePlace(RandomValue.getRoad());
        hotel.setOutTime(System.currentTimeMillis());
        hotel.setRoomno("304");
        hotel.setSex("女");
        return hotel;
    }

    @Override
    public Hotel format(Hotel hotel) {
        return hotel;
    }

    @Override
    public void sendData(RabbitMqParams params, Hotel hotel) {
        RabbitProductClient client=new RabbitProductClient(params.getExchangName(),params.getHost(),params.getPort(),params.getUsername(),params.getPassword(),params.getExchangeType());
        try {
            client.sendMessage(JSON.toJSONString(hotel),params.getRouteKey());
            logger.info("旅馆数据发送成功: " + JSON.toJSONString(hotel));
        } catch (Exception e) {
            logger.error("发送旅馆数据出错");
            e.printStackTrace();
        }
    }
}

4. Use environment different specific roles Strategy load (environmental load different roles thread real policy role of different types of data acquisition is completed, the package, pushed)

@Component
public class ProcessStarter implements ApplicationRunner {
	@Override
	public void run(ApplicationArguments args) throws Exception {
		logger.info("模拟数据启动O(∩_∩)O~O(∩_∩)O~O(∩_∩)O~O(∩_∩)O~O(∩_∩)O~");
		try {
			//停车场数据
			if (true) {
				logger.info("picPark data product O(∩_∩)O~");
				PicParkDataHandle handle=new PicParkDataHandle();
				RabbitMqParams params=new RabbitMqParams();
				params.rabbitInit();
				params.setExchangName("xx_xx");
				params.setRouteKey("xx.xx.2.*");
				DispatchThread<PicPark> dispatchThread=new DispatchThread(handle,params);
				Thread picThread = new Thread(dispatchThread);
				picThread.setName("PicParkThread");
				picThread.start();
				ThreadMonitor.getInstance().addThreadMonitor(picThread);
			}	
			if (true) {
				logger.info("hotel data product O(∩_∩)O~");
				HotelHandle handle=new HotelHandle();
				RabbitMqParams params=new RabbitMqParams();
				params.rabbitInit();
				params.setExchangName("xx_xx");
				params.setRouteKey("xx.xx.2");
				DispatchThread<Hotel> dispatchThread=new DispatchThread(handle,params);
				Thread hotelThread = new Thread(dispatchThread);
				hotelThread.setName("HotelThread");
				hotelThread.start();
				ThreadMonitor.getInstance().addThreadMonitor(hotelThread);
			}

			logger.info("模拟数据启动程序启动完成//(≧▽≦)//~~//(≧▽≦)//~~//(≧▽≦)//~");
		} catch (Exception e) {
		   logger.error("模拟数据启动程序启动时发生异常(╯﹏╰)(╯﹏╰)"+e.getMessage(),e);
		}
		
	}
}


 

Published 29 original articles · won praise 2 · Views 1154

Guess you like

Origin blog.csdn.net/weixin_42232931/article/details/104079963