ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 디자인패턴 Delegate pattern 예제
    java 2021. 4. 4. 21:58

    객체 지향 디자인 패턴의 한 종류인 Delegate pattern구현

     

    객체를 위임시키기 위한 Delegator와 같은 interface를 상속받는 클래스들이 필요합니다.

     

     - VehiclaManagerService Interface

    public interface VehicleManagerService{
    	public String myBehicle();
    }

     

    - VehiclaManagerService 구현클래스

    public class CarManagerServiceImpl implements VehicleManagerService{
    	@Override
    	public String myBehicle() {
    		// TODO Auto-generated method stub
    		return "Car";
    	}
    }
    public class BusManagerServiceImpl implements VehicleManagerService{
    	@Override
    	public String myBehicle() {
    		// TODO Auto-generated method stub
    		return "Bus";
    	}
    }
    public class BoatManagerServiceImpl implements VehicleManagerService{
    	@Override
    	public String myBehicle() {
    		return "Boat";
    	}
    }

     

    - VehicleEnum

    public enum VehicleEnum {
    	_BUS,
    	_CAR,
    	_BOAT
    }

    - DelegatorVehicleManagerDelegator : delegate역할을 수행하는 delegator

    public class VehicleManagerDelegator {
    	private VehicleManagerService vehicleManager;
    	
    	public VehicleManagerDelegator(VehicleEnum behicle) {
    		switch(behicle) {
    		case _BOAT:
    			vehicleManager = new BoatManagerServiceImpl();
    			break;
    		case _BUS:
    			vehicleManager = new BusManagerServiceImpl();
    			break;
    		case _CAR:
    			vehicleManager = new CarManagerServiceImpl();
    			break;
    		default:
    			break;
    		}
    	}
    	public VehicleManagerService getVehicleManager() {
    		return vehicleManager;
    	}
    	public void setVehicleManager(VehicleManagerService vehicleManager) {
    		this.vehicleManager = vehicleManager;
    	}
    }

    - main

    public class DelegatorMain {
    	public static void main(String[] args) {
    		VehicleManagerDelegator vehicle;
    		
    		vehicle = new VehicleManagerDelegator(VehicleEnum._BUS);
    		String myVehicle = vehicle.getVehicleManager().myBehicle();
    		System.out.println(myVehicle); //Bus
    		
    		VehicleManagerService vm = new VehicleManagerDelegator(VehicleEnum._BOAT).getVehicleManager();
    		myVehicle = vm.myBehicle();
    		System.out.println(myVehicle); //Boat
    	}
    }

    댓글

Designed by Tistory.