装饰模式
简单的装饰代码
class Person{
private String name;
public Person(String name) {
this.name = name ;
}
public void WearTshirt() {
Console.Write("大T恤");
}
public void WearBigTrouser() {
Console.Write("垮裤");
}
public void WearSneakers() {
Console.Write("破球鞋");
}
public void WearTie() {
Console.Write("领带");
}
public void Show() {
Console.WriteLine(name);
}
}
public static void main(String[] args) {
Person xc = ne Person("小菜");
System.out.println("第一只种装扮");
xc.WearTshirt();
xc.WearBigTrouser();
xc.WearSnakers();
xc.show();
System.out.println("第二只种装扮");
xc.WearSuilt();
xc.WearTie();
xc.WearShoes();
xc.show();
}
增加抽象类
class Person{
private String name;
public person(String name) {
this.name = name;
}
public void show() {
System.out.println(name);
}
}
abstract class Finery{
public abstract void show();
}
//大T恤
class Tshirts extends Finery{
public void show() {
System.out.println("大T恤");
}
}
//垮裤
class BigTrouser extends Finery{
public void show() {
System.out.println("垮裤");
}
}
//.....
static void Main(String[] args) {
Person xc = new Person("小菜");
System.out.println("第二只种装扮");
Finery dtx = new Tshirts();
Finery kk = new BigTrouser();
Finery pqx = new Sneakers();
dtx.show();
kk.show();
pqx.show();
xc.show();
System.out.println("第二只种装扮");
xz.show();
kk.show();
px.show();
xc.show();
}
装饰模式:动态地给一个对象添加一些图外的职责,就增加功能来说,装饰模式比生成子类更为灵活.
//Component
abstract class Compoent {
public abstract void Operation();
}
//ConcreteCompoent
class ConcreteCompoent extends Component{
public void Operation() {
System.out.println("具体对象的操作");
}
}
//Decorator
abstract class Decorator extends Compoent{
protected Compoent component ;
public void SetCompoent(Compoent compoent) {
this.compoent = compoent;
}
public void Operation() {
if(compoet !=null) {
compoent.Operation();
}
}
}
//ConcreteDecorator A
class ConcreteDecoratorA extends Decorator{
private String addedstate;
public void Operation() {
base.Operation();
addedState = "new State";
System.out.println("具体装饰对象A的操作");
}
}
最终版本
class Person{
public Person() {
}
private String name;
public Person(String name) {
this.name = name;
}
public void show() {
System.out.println(name);
}
}
class Finery extends Person{
protected Person component;
public void Decorate(Person compoent) {
this.compoent = component;
}
public void show() {
if(compoent != null) {
compoent.Show();
}
}
}
static void main(String[] args) {
Person xc = new Person("小菜");
Sneakers pqx = new Sneakers();
BigTrouser kk = new BigTourser();
Tshirts dtx = new Tshirts();
pqx.Decorate(xc);
kk.Decorate(pqx);
dtx.Decorate(kk);
dtx.show();
}
装饰模式详解
1240

被折叠的 条评论
为什么被折叠?



