装饰模式(解决多继承的问题):不改变原来功能,新增添功能——Decorator
适配器模式:不改变原来功能,改变新的接口
一、适配器模式
//有特殊功能的类
class Adapt{
public void s_fun(){
System.out.println("特殊功能方法!");
}
}
interface target{
public void fun();//接口方法
}
//实现接口类
class Contarget implements target{
@Override
public void fun() {
System.out.println("普通方法!");
}
}
/**
* 类适配器
*/
//适配器类——继承了具有特殊方法的类,并实现接口,重写父类方法
class Adapter extends Adapt implements target{
@Override
public void fun() {
super.s_fun();
}
}
/**
* 对象适配器
*/
class Adapter2 implements target{
private Adapt adapt;
public Adapter2(Adapt adapt) {
this.adapt = adapt;
}
@Override
public void fun() {
this.adapt.s_fun();
}
}
public class Demo323_2 {
public static void main(String[] args) {
Adapter adapter = new Adapter();
adapter.fun();
Adapt adapt = new Adapt();
Adapter2 adapter2 = new Adapter2(adapt);
adapter2.fun();
}
}
二、装饰器模式
装饰器模式(Decorator Pattern)——动态地给一个对象添加一些额外的职责。
——四个角色:
(1)Component(抽象构件):是一个接口或抽象类,用来定义最核心的对象,即最原始的对象。
注:在装饰模式中,必然有一个最基本、最核心、最原始的接口或抽象类充当Component抽象构件。
(2)ConcreteComponent(具体构件):最核心、最原始、最基本的接口或抽象类的实现,被装饰的对象。
(3)Decorator(装饰角色):一般是一个抽象类。用于实现接口或抽象方法,但其中并不一定具有抽象方法。在它的属性中必须有一个private变量指向Component(抽象构件)。
(4)具体装饰角色:具体的装饰类,把最核心、最原始、最基本的东西装饰成其他东西。
//抽象构件
abstract class Component {
//抽象方法
public abstract void operate();
}
//具体构件
class ContreteComponent extends Component{
@Override
public void operate() {
System.out.println("operate()");
}
}
//装饰角色
abstract class Decorator extends Component {
private Component component = null;
//通过构造函数传参
public Decorator(Component component) {
this.component = component;
}
//重写父类抽象方法
@Override
public void operate() {
this.component.operate();//调用属性的方法
}
}
//具体的装饰类
class ConcreteDecorator extends Decorator {
//定义被装饰者
public ConcreteDecorator(Component component) {
super(component);
}
//修饰方法
private void fun1() {
System.out.println("修饰方法");
}
//重写父类方法
public void operator() {
this.fun1();//调用修饰方法
super.operate();//调用父类方法
}
}
//具体装饰类
class ConcreteDecorator2 extends Decorator {
//定义被装饰者
public ConcreteDecorator2(Component component) {
super(component);
}
//修饰方法
public void fun2(){
System.out.println("修饰方法二");
}
//重写父类方法
public void operator() {
this.fun2();//修饰方法
super.operate();//父类方法
}
}