设计模式相关

一、常见的设计模式

1.简单工厂方法

2.装饰器模式

定义:在不改变原有对象的基础上,将功能附加到对象上。
UML类图:

Component
+operation()
ConcreteComponent
+operation()
Decorator
-component
+operation()
ConcreteDecorator1
+operation()
ConcreteDecorator2
+operation()

实现:

public class DecoratorTest {
    public static void main(String[] args) {
          Component component=  new ConreteDecorator1( new ConreteDecorator2(new ConcreteComponent() ) );
          component.operation();
    }
}
interface Component{
    void operation();
}
class ConcreteComponent implements Component{

    @Override
    public void operation() {
        System.out.println("原始功能.");
    }
}
abstract class Decorator implements Component{
    Component component;

    public Decorator(Component component) {
        this.component=component;
    }
}

class ConreteDecorator1 extends Decorator{

    public ConreteDecorator1(Component component) {
        super( component );
    }

    @Override
    public void operation() {
        System.out.println("增加功能1.");
        component.operation();
    }
}

class ConreteDecorator2 extends Decorator{

    public ConreteDecorator2(Component component) {
        super( component );
    }

    @Override
    public void operation() {
        System.out.println("增加功能2.");
        component.operation();
    }
}

3.适配器模式

定义:将一个类接口转换成客户希望的另一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的类可以一起工作。
UML类图:

client
target
+operation()
adaptor
+operation()
adaptee
+specificOperation()

实现:

public class AdapterTest1 {
    public static void main(String[] args) {
        Adaptee adaptee=new Adaptee();

        Target target = new Adapter( adaptee );
        target.basicFunction();

    }
}
class Adaptee{
    public int extraFunction(){
        return 777;
    }
}
interface Target{
    int basicFunction();
}
// Object Adapter
class Adapter implements Target{

    private Adaptee adaptee;

    public Adapter(Adaptee adaptee) {
        this.adaptee=adaptee;
    }

    @Override
    public int basicFunction() {
        int i=adaptee.extraFunction();
        //  ......
        System.out.println(String.format( "额外功能:%d",i));
        return 555;
    }
}

二、不同设计模式的区别

1.装饰器模式和适配器模式对比

模式特点区别
装饰器模式不改变原有类,在原有类基础上增加新功能不是要改变被装饰对象的接口,而是恰恰要保持原有的接口
适配器模式现有接口无法满足,新建实现类,实现类中定义对象来扩展功能将一个接口转变成另一个接口,它的目的是通过改变接口来达到重复使用的目的
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值