>  기사  >  Java  >  Java 장식 모드 학습

Java 장식 모드 학습

黄舟
黄舟원래의
2017-10-13 10:19:251753검색

이 글은 주로 Java 디자인 패턴 학습에서 장식 모드 관련 정보를 자세히 소개합니다. 관심 있는 친구들이 참고할 수 있습니다.

장식 모드: 객체에 몇 가지 추가 요소를 동적으로 추가합니다. 기능적으로 장식 모드는 하위 클래스를 생성하는 것보다 더 유연합니다.

장점: 데코레이팅 클래스와 데코레이팅된 클래스는 서로 결합되지 않고 독립적으로 개발할 수 있습니다. 데코레이션 모드는 구현 클래스의 기능을 동적으로 확장할 수 있는 대체 모드입니다.

단점: 다층 장식이 더 복잡합니다.

예: 사람을 위한 옷 구성

1: 코드 구조 다이어그램

2: 사람 클래스 생성(ConcreteComponent)


package DecoratorModel;

/**
 * 2017-10-9 10:39:09
 * 装饰器设计模式
 * Person 类 ConcreteComponent
 * @author 我不是张英俊
 *
 */
public class Person {

  public Person(){}
  
  private String name;
  public Person(String name){
    this.name=name;
  }
  
  public void Show(){
    System.out.println("装扮的"+name);
  }
}

3: 의류 클래스


package DecoratorModel;

/**
 *服饰类(Decorator)
 * @author 我不是张英俊
 *
 */
public class Finery extends Person{

  protected Person component;
  //打扮
  public void Decorate(Person component){
    this.component=component;
  }
  
  public void Show(){
    if(component!=null){
      component.Show();
    }
  }
}

4: 특정 의류 Category


public class Tshirts extends Finery {
  public void Show(){
    System.out.println("大T恤");
    super.Show();
    }
}

public class BigTrouser extends Finery {
  public void Show(){
    System.out.println("垮裤");
    super.Show();
  }
}

public class Sneakers extends Finery {
  public void Show(){
    System.out.println("破球鞋");
    super.Show();
    }
}

public class Suit extends Finery {
  public void Show(){
    System.out.println("西装");
    super.Show();
  }
}

public class Tie extends Finery {
  public void Show(){
    System.out.println("领带");
    super.Show();
  }
}

public class LeatherShoes extends Finery {
  public void Show(){
    System.out.println("皮鞋");
    super.Show();
  }
}

5: 테스트 카테고리


public class test {

  public static void main(String[] args) {
    Person xc=new Person("旺财");    
    Sneakers pqx=new Sneakers();
    BigTrouser kk=new BigTrouser();
    Tshirts dtx=new Tshirts();
    pqx.Decorate(xc);
    kk.Decorate(pqx);
    dtx.Decorate(kk);
    dtx.Show();
  }

}

6: Console

큰 티셔츠
가방 바지
깨진 운동화
번영을 위한 옷차림

위 내용은 Java 장식 모드 학습의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.