Java多接口案例如何开发

wen java案例 27

本文目录导读:

Java多接口案例如何开发

  1. 基本接口定义
  2. 接口默认方法和静态方法
  3. 接口继承
  4. 实用示例:支付系统
  5. 测试类
  6. 最佳实践
  7. 常见问题与注意事项

我来详细介绍Java多接口开发的案例,包括接口定义、实现类和测试代码。

基本接口定义

定义多个功能接口

// 播放器接口
public interface Player {
    void play();
    void pause();
    void stop();
}
// 录音器接口
public interface Recorder {
    void startRecording();
    void stopRecording();
}
// 网络连接接口
public interface NetworkConnectable {
    void connect();
    void disconnect();
    boolean isConnected();
}

创建实现类(实现多个接口)

// 智能手机类 - 实现多个接口
public class SmartPhone implements Player, Recorder, NetworkConnectable {
    private String model;
    private boolean isConnected = false;
    public SmartPhone(String model) {
        this.model = model;
    }
    // Player接口实现
    @Override
    public void play() {
        System.out.println(model + " 正在播放音乐");
    }
    @Override
    public void pause() {
        System.out.println(model + " 暂停播放");
    }
    @Override
    public void stop() {
        System.out.println(model + " 停止播放");
    }
    // Recorder接口实现
    @Override
    public void startRecording() {
        System.out.println(model + " 开始录音");
    }
    @Override
    public void stopRecording() {
        System.out.println(model + " 停止录音");
    }
    // NetworkConnectable接口实现
    @Override
    public void connect() {
        isConnected = true;
        System.out.println(model + " 已连接网络");
    }
    @Override
    public void disconnect() {
        isConnected = false;
        System.out.println(model + " 已断开网络");
    }
    @Override
    public boolean isConnected() {
        return isConnected;
    }
    // 自定义方法
    public void makeCall(String number) {
        if (isConnected) {
            System.out.println("正在拨打:" + number);
        } else {
            System.out.println("请先连接网络");
        }
    }
}

接口默认方法和静态方法

// 包含默认方法和静态方法的接口
public interface MediaDevice {
    // 抽象方法
    void start();
    void stop();
    // 默认方法
    default void displayInfo() {
        System.out.println("这是一个媒体设备");
    }
    // 静态方法
    static String getDeviceType() {
        return "Media Device";
    }
}
// 另一个接口
public interface Diagnostic {
    default void runDiagnostic() {
        System.out.println("运行标准诊断...");
    }
    static String getVersion() {
        return "1.0.0";
    }
}
// 复杂的实现类
public class MultiMediaPlayer implements Player, MediaDevice, Diagnostic {
    @Override
    public void play() {
        System.out.println("多媒体播放器开始播放");
    }
    @Override
    public void pause() {
        System.out.println("多媒体播放器暂停");
    }
    @Override
    public void stop() {
        System.out.println("多媒体播放器停止");
    }
    @Override
    public void start() {
        System.out.println("设备启动");
    }
    // 可以重写默认方法
    @Override
    public void displayInfo() {
        System.out.println("这是一个多媒体播放器");
    }
    @Override
    public void runDiagnostic() {
        System.out.println("运行多媒体播放器专属诊断...");
    }
}

接口继承

// 基础接口
public interface Animal {
    void eat();
    void sleep();
}
// 扩展接口
public interface FlyingAnimal extends Animal {
    void fly();
}
public interface SwimmingAnimal extends Animal {
    void swim();
}
// 实现多个继承的接口
public class Duck implements FlyingAnimal, SwimmingAnimal {
    @Override
    public void eat() {
        System.out.println("鸭子正在吃");
    }
    @Override
    public void sleep() {
        System.out.println("鸭子正在睡觉");
    }
    @Override
    public void fly() {
        System.out.println("鸭子正在飞");
    }
    @Override
    public void swim() {
        System.out.println("鸭子正在游泳");
    }
}

实用示例:支付系统

// 支付接口
public interface Payment {
    void pay(double amount);
    void refund(double amount);
}
// 安全验证接口
public interface SecureVerifiable {
    boolean verifyIdentity(String credentials);
    boolean verifyAmount(double amount);
}
// 日志记录接口
public interface Loggable {
    void log(String message);
    default void logTransaction(String transactionId, double amount) {
        log("交易 " + transactionId + " 金额: " + amount);
    }
}
// 银行支付实现
public class BankPayment implements Payment, SecureVerifiable, Loggable {
    private String accountNumber;
    public BankPayment(String accountNumber) {
        this.accountNumber = accountNumber;
    }
    @Override
    public void pay(double amount) {
        if (verifyAmount(amount)) {
            logTransaction("PAY-" + System.currentTimeMillis(), amount);
            System.out.println("银行支付 " + amount + " 元成功");
        }
    }
    @Override
    public void refund(double amount) {
        logTransaction("REF-" + System.currentTimeMillis(), amount);
        System.out.println("退款 " + amount + " 元成功");
    }
    @Override
    public boolean verifyIdentity(String credentials) {
        return credentials != null && !credentials.isEmpty();
    }
    @Override
    public boolean verifyAmount(double amount) {
        return amount > 0 && amount <= 1000000;
    }
    @Override
    public void log(String message) {
        System.out.println("[银行日志] " + message);
    }
}

测试类

public class InterfaceDemo {
    public static void main(String[] args) {
        // 测试智能手机
        System.out.println("=== 智能手机测试 ===");
        SmartPhone phone = new SmartPhone("iPhone 14");
        phone.connect();
        phone.play();
        phone.pause();
        phone.startRecording();
        phone.stopRecording();
        phone.makeCall("10086");
        // 测试多媒体播放器
        System.out.println("\n=== 多媒体播放器测试 ===");
        MultiMediaPlayer player = new MultiMediaPlayer();
        player.start();
        player.play();
        player.displayInfo();  // 重写的默认方法
        player.runDiagnostic(); // 重写的默认方法
        System.out.println("设备类型: " + MediaDevice.getDeviceType());
        System.out.println("诊断版本: " + Diagnostic.getVersion());
        // 测试鸭子(接口继承)
        System.out.println("\n=== 鸭子测试 ===");
        Duck duck = new Duck();
        duck.eat();
        duck.fly();
        duck.swim();
        // 测试支付系统
        System.out.println("\n=== 支付系统测试 ===");
        BankPayment payment = new BankPayment("6222021234567890");
        if (payment.verifyIdentity("user123")) {
            payment.pay(999.99);
            payment.refund(100.00);
        }
        // 多态使用示例
        System.out.println("\n=== 多态示例 ===");
        Player playerRef = new SmartPhone("Samsung Galaxy");
        Recorder recorderRef = new SmartPhone("华为P60");
        playerRef.play();
        recorderRef.startRecording();
        // 类型检查
        if (playerRef instanceof NetworkConnectable) {
            NetworkConnectable net = (NetworkConnectable) playerRef;
            net.connect();
        }
    }
}

最佳实践

接口设计原则

// 接口分离原则(ISP)
// 错误示例:大而全的接口
interface AllInOne {
    void play();
    void record();
    void draw();
    void calculate();
}
// 正确示例:拆分为小接口
interface MediaPlayer {
    void play();
    void stop();
}
interface Recorder {
    void record();
}
interface Drawable {
    void draw();
}

工厂模式结合接口

// 工厂类
public class DeviceFactory {
    public static Player createPlayer(String type) {
        switch (type.toLowerCase()) {
            case "smartphone":
                return new SmartPhone("通用手机");
            case "multimedia":
                return new MultiMediaPlayer();
            default:
                throw new IllegalArgumentException("未知设备类型: " + type);
        }
    }
}
// 使用工厂
Player player = DeviceFactory.createPlayer("smartphone");
player.play();

常见问题与注意事项

  1. 默认方法冲突解决:当两个接口有相同默认方法时,必须重写
  2. 接口中不能有实例变量
  3. 接口方法默认是public abstract
  4. 接口中定义的常量默认是public static final
  5. 一个类可以实现多个接口,但只能继承一个类

这个多接口案例涵盖了从基础到进阶的各种场景,有助于理解Java接口的强大功能。

抱歉,评论功能暂时关闭!