总述
它能够灵活地运用2个类的特性,来生成兼具2者特性的实例。
结构
一个类型是用户想要使用来生成他想要的对象的类型,是主角。另一个类型只是个组成部分,是配角。或者可以理解为,一个是一把手,另一个是二把手,一个是核心,另一个是辅助。当辅助的那个通过遵守接口规定,来当好自己的辅助角色。当核心的使用抽象类来做好自己的核心位置。没办法,核心没有辅助也难做啊,于是核心使用的抽象类中还必须给辅助所遵循的协议留下一个位置。核心和辅助在这种方式下配合,就无往而不利了。
类图
结果
法系核心买鸡买眼
法系核心回血回蓝
物理核心买鸡买眼
物理核心回血回蓝
Process finished with exit code 0
调用
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
Carry one = new Carry1();
one.setSupport(new Support1());
one.winTheBattle();
Carry two = new Carry1();
two.setSupport(new Support2());
two.winTheBattle();
Carry three = new Carry2();
three.setSupport(new Support1());
three.winTheBattle();
Carry four = new Carry2();
four.setSupport(new Support2());
four.winTheBattle();
}
}
核心抽象类
package com.company;
public abstract class Carry {
protected Support support;
public void setSupport(Support support) {
this.support = support;
}
public void winTheBattle() {}
}
核心1
package com.company;
public class Carry1 extends Carry {
@Override
public void winTheBattle() {
super.winTheBattle();
System.out.print("法系核心");
this.support.workOfSupport();
}
}
核心2
package com.company;
public class Carry2 extends Carry {
@Override
public void winTheBattle() {
super.winTheBattle();
System.out.print("物理核心");
this.support.workOfSupport();
}
}
辅助接口
package com.company;
public interface Support {
void workOfSupport();
}
辅助1
package com.company;
public class Support1 implements Support {
@Override
public void workOfSupport() {
System.out.println("买鸡买眼");
}
}
辅助2
package com.company;
public class Support2 implements Support {
@Override
public void workOfSupport() {
System.out.println("回血回蓝");
}
}
多谢捧场
如果您觉得我的文章有价值,那么赏脸打赏一个,鄙人感激不尽。不过,不打赏看看也是好的,如果有不对的地方,还请您多多指正。
网友评论