Java 接口标准定义  工厂设计模式  代理设计模式

本文通过代码示例展示了接口在类设计中的应用,包括USB设备的接口定义及其实现,以及工厂设计模式的使用。此外,还介绍了泛型改进的工厂模式,用于创建不同类型的食品对象,并通过代理设计模式来演示如何在真实主题执行操作前进行准备工作和后续清理工作。

接口标准定义

package com.msc.example;
interface IUSB{
    public boolean check() ;
    public void work() ;

}
class Computer{
    public void plugin(IUSB iusb){
        if (iusb.check()){
            iusb.work();
        }else{
            System.out.println("硬件设备出错");
        }
    }
}
class keyBoard implements IUSB{
    public boolean check() {
        return  true ;
    }
    @Override
    public void work() {
        System.out.println("键盘开始工作");
    }
}
class Print implements IUSB{
    public boolean check() {
        return  false ;
    }
    @Override
    public void work() {
        System.out.println("打印机开始工作");
    }
}
public class InterfaceDemo {
    public static void main(String[] args) {
    Computer computer = new Computer() ;
    computer.plugin(new keyBoard());
    computer.plugin(new Print());
    }
}

工厂设计模式
泛型改进工厂设计模式
在这里插入图片描述

package com.msc.example;
interface IFood{
     public void eat() ;
}
class Factory{
    public static IFood getInstance(String classname) {
        switch(classname){
            case "bread": {
                return new Bread();
            } case "milk" : {
                return new Milk() ;
            } default:{
                return null;
            }
        }
    }
}
class Bread implements IFood{
    @Override
    public void eat(){
        System.out.println("吃面包");
    }
}
class Milk implements IFood{
    @Override
    public void eat() {
        System.out.println("喝牛奶");
    }
}

public class FactoryModel {
    public static void main(String[] args) {
        IFood ifood = Factory.getInstance("milk");
        ifood.eat();
        ifood = Factory.getInstance("bread");
        ifood.eat();
    }
}

代理设计模式
在这里插入图片描述

package com.msc.example;
interface IEat{
    public void get() ;
}
class EatNeed implements IEat{
    public void get() {
        System.out.println("【真实主题】获得食物开吃");
    }
}
class EatProxy implements IEat{
    private IEat eat ;
    public EatProxy () {} ;
    public EatProxy(IEat eat){
        this.eat = eat ;
    }
    public void get() {
        this.prepare() ;
        this.eat.get() ;
        this.clear() ;
    }
    public void prepare() {	// 准备过程
        System.out.println("【代理主题】1、精心购买食材。") ;
        System.out.println("【代理主题】2、小心的处理食材。") ;
    }
    public void clear() {
        System.out.println("【代理主题】3、收拾碗筷。");
    }
}
public class ProxyModel {
    public static void main(String[] args) {
        IEat eat = new EatProxy(new EatNeed()) ;
        eat.get() ;
    }
}

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

隔壁de小刘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值