상용 디자인 모델 의 실현 및 Netty 의 디자인 모델

23046 단어
1. 관찰자 모드
두 가지 역할 이 있 습 니 다. 관찰자 와 피 관찰자 가 있 습 니 다.피 관찰자 가 메 시 지 를 보 내 면 등 록 된 관찰 자 는 그 메 시 지 를 받 고 등록 되 지 않 은 관찰 자 는 받 지 않 는 다.
//       
interface Observer{
    //     
    void notify(String message);
}

//      
interface Observed{
    //     
    void registerObserver(Observer o);
    //     
    void removeObserver(Observer o);
    //     
    void notifyObserver();
}

//        (  )
class Gril implements Observed{
    //       
    private String message;
    //      
    List observerList;

    public Gril(){
        observerList=new ArrayList<>();
    }

    @Override
    public void registerObserver(Observer o) {
        //       
        observerList.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
        //       
        observerList.remove(o);
    }

    @Override
    public void notifyObserver() {
        //         
        for(Observer o:observerList){
            o.notify(message);
        }
    }

    public void setMeesage(String message){
        this.message=message;
    }
}

//     
class Handsome_Boy implements Observer{
    @Override
    public void notify(String message) {
        System.out.println("         :"+message);
    }
}
class Lao_Wang implements Observer{
    @Override
    public void notify(String message) {
        System.out.println("      :"+message);
    }
}
class Gay implements Observer{
    @Override
    public void notify(String message) {
        System.out.println("       :"+message);
    }
}
//    
public class observer_test {
    public static void main(String[] args) {
        //              
        Gril gril=new Gril();
        Handsome_Boy boy=new Handsome_Boy();
        Gay gay=new Gay();
        Lao_Wang wang=new Lao_Wang();

        //     
        gril.registerObserver(boy);
        gril.registerObserver(wang);

        //        
        gril.setMeesage("     ");
        gril.notifyObserver();
    }
}

Netty 에서 의 응용: NioSocketChannel. writeAndFlush ().
2. 책임 체인 모드
책임 체인 모델 은 여러 대상 이 같은 요 구 를 처리 할 수 있 도록 여러 대상 을 하나의 체인 으로 연결 시 켜 사건 을 이 체인 에서 전파 시 키 고 체인 의 모든 노드 가 전 파 를 중지 할 수 있다.Netty 를 잘 아 는 친구 들 은 이런 디자인 모델 을 알 고 있 을 것 이다. pipeline 은 마치 책임 체인 과 같 고 Channel Handler 는 그 중에서 논 리 를 처리 하 는 노드 이다.
//             
abstract class AbstractHandler {
    //        ,        ,          
    AbstractHandler nextHandler;
    //         
    public void Execute(String message) {
        write(message);
   //
        if (nextHandler != null)
            nextHandler.Execute(message);
    }
    //          
    public void setNextHandler(AbstractHandler handler) {
        this.nextHandler = handler;
    }
    //
    abstract void write(String message);
}

//     A
class HandlerA extends AbstractHandler {
    //       
    @Override
    void write(String message) {
        System.out.println("     A  :" + message);
    }
}
//     B
class HandlerB extends AbstractHandler {
    @Override
    void write(String message) {
        System.out.println("     B  :" + message);
    }
}
//     C
class HandlerC extends AbstractHandler {
    @Override
    void write(String message) {
        System.out.println("     C  :" + message);
    }
}
//    
public class Chain_ResponsibilityTest {
    public static void main(String[] args) {
        //           
        AbstractHandler a = new HandlerA();
        AbstractHandler b = new HandlerB();
        AbstractHandler c = new HandlerC();

        //          
        a.setNextHandler(b);
        b.setNextHandler(c);

        //        
        a.Execute("  ");
    }
}

마지막 으로 ABC 는 링크 순서대로 출력 할 겁 니 다.
 
3. 단일 모드
단일 모드 의 특징 은 하나의 전역 에 하나의 변수 만 있 고 만 들 때 스 레 드 가 안전 하 다 는 것 입 니 다.일반적인 단일 모드 구현 코드:
public class Singleton {
    private static Singleton singleton;
    private Singleton(){}
    public static Singleton getInstance(){
        if(singleton==null){
            synchronized (Singleton.class){
                if(singleton==null)
                    singleton=new Singleton();
            }
        }
        return singleton;
    }
}

중요 한 것 은 민영화 구조 함수 에 있 습 니 다. 그리고 개인 적 인 정적 전역 변 수 를 정의 하여 현재 클래스 의 인 스 턴 스 를 저장 하 는 데 사 용 됩 니 다.인 스 턴 스 를 가 져 오 는 방법 을 외부 에 제공 합 니 다. 현재 인 스 턴 스 변수 가 비어 있 지 않 으 면 실례 화 되 었 음 을 설명 하고 바로 돌아 갑 니 다.그렇지 않 으 면 실례 화 를 진행 합 니 다. 여러 라인 이 동시에 if 에 들 어가 실례 화 를 반복 하 는 것 을 방지 하기 위해 서 는 synchronized 를 추가 해 야 합 니 다.또 게 으 른 사람, 굶 주 린 사람의 구분 도 있다.위의 코드 는 게으름뱅이 단일 예 모드 입 니 다. 즉, 인 스 턴 스 를 가 져 올 때 만 듭 니 다. 이것 은 Netty 의 로드 지연 과 같은 사상 입 니 다.한편, 굶 주 린 사람 은 인 스 턴 스 변 수 를 정의 할 때 직접 예화 되 고 구조 함 수 를 민영화 한 다음 에 인 스 턴 스 를 얻 는 방법 으로 이 변 수 를 직접 되 돌려 주면 된다.단일 모드 가 Netty 에서 의 응용: ReadTimeoutException 등.
 
4. 전략 모드
간단하게 말 하면 하나의 행동 이나 알고리즘 은 실행 할 때 변경 할 수 있 습 니 다. 이것 은 전략 모드 입 니 다.실행 중인 데이터 에 따라 어떤 논 리 를 실행 할 지 자동 으로 선택해 야 할 때 전략 모드 를 사용 할 수 있 습 니 다.다음은 간단하게 실현 하 겠 습 니 다.
//        
interface Calculate{
    int operation(int num1,int num2);
}

//
class StrategyAdd implements Calculate{
    @Override
    public int operation(int num1,int num2) {
        return num1+num2;
    }
}
class StrategyMultiply implements Calculate{
    @Override
    public int operation(int num1, int num2) {
        return num1*num2;
    }
}
//           
class Use{
    private Calculate calculate;
    //
    public Use(Calculate calculate){
        this.calculate=calculate;
    }
    public int execute(int num1,int num2){
        //           operation  
        return calculate.operation(num1,num2);
    }
}
public class Strategy {
    //    
    public static void main(String[] args) {
        //     main  ,              ,args               
        //
        if(args.length==0){
             Use use=new Use(new StrategyAdd());
             System.out.println(use.execute(5,5));//10
        }else {
            Use use1=new Use(new StrategyMultiply());
            System.out.println(use1.execute(5,5));//25
        }
    }
}

Netty 에서 의 응용: DefaultEventExecutor Chooser Factor - new Chooser
 
5. 장식 자 모드
기 존 유형의 코드 를 수정 하지 않 아 도 이 유형의 대상 에 다른 효 과 를 추가 할 수 있다.하나의 기능 을 확대 하려 면 이런 디자인 모델 을 사용 할 수 있다.그러나 이런 디자인 모델 의 단점 도 매우 뚜렷 하고 추가 적 인 코드 가 있 을 것 이다. 계승 하 는 등급 이 많아 지면 논리 도 더욱 복잡 해진 다.
//        ,      
interface Goods{
    float getPrice();
}

//        ,    (  )
class Car implements Goods{
    private float Price;
    public Car(float price){
        this.Price=price;
    }
    @Override
    public float getPrice() {
        return Price;
    }

}

//      ,         。     ,                    get  。
//
class On_Sale implements Goods{
    private Goods goods;
    public On_Sale(Goods goods){
        this.goods=goods;
    }
    @Override
    public float getPrice() {
        return this.goods.getPrice();
    }
}

//      (    ,      )
class Car_Knock extends On_Sale{
    //    
    private float amount;
    public Car_Knock(float amount,Goods goods){
        super(goods);
        this.amount=amount;
    }
    @Override
    public float getPrice() {
        return super.getPrice()-amount;
    }
}

//      
class Car_Discount extends On_Sale{
    //    
    private int discount;
    public Car_Discount(int discount,Goods goods){
        super(goods);
        this.discount=discount;
    }
    @Override
    public float getPrice() {
        return super.getPrice()*discount/10;
    }
}
//    
public class decorator {
    public static void main(String[] args) {
        //
        Goods goods=new Car(120000);
        //   1000 
        goods=new Car_Knock(1000,goods);
        //         8 
        goods=new Car_Discount(8,goods);
        System.out.println(goods.getPrice());
    }
}

Netty 의 응용 프로그램: WrappedByteBuf, Unreleasable ByteBuf, Simple LeakAwareByteBuf.첫 번 째 종 류 는 장식 자의 아버지 류 에 해당 하고 그 다음 두 가 지 는 장식 류 이 며 ByteBuf 는 원형 이다.

좋은 웹페이지 즐겨찾기