C#中接口设计相关原则

在C#中,接口(Interface)是一种引用类型,它定义了一个契约,指定了一个类必须实现的成员(属性、方法、事件、索引器)。接口不提供这些成员的实现,只指定成员必须按照特定的方式被实现。

1、使用接口隔离原则 (ISP)

将较大的接口划分为更小、更具体的接口,以遵守 ISP,并确保实现类只需要实现它们使用的方法。

// Bad example  
  
// A single interface for both lights and thermostats  
public interface IDevice  
{  
    void TurnOn();  
    void TurnOff();  
    void SetTemperature(int temperature);  
}  
  
public class SmartLight : IDevice  
{  
    public void TurnOn()  
    {  
        Console.WriteLine("Smart light turned on");  
    }  
  
    public void TurnOff()  
    {  
        Console.WriteLine("Smart light turned off");  
    }  
  
    public void SetTemperature(int temperature)  
    {  
        // Unsupported operation for a light  
        Console.WriteLine("Cannot set temperature for a light");  
    }  
}  
  
// Good example   
  
// Interface for a light device  
public interface ILight  
{  
    void TurnOn();  
    void TurnOff();  
}  
  
// Interface for a thermostat device  
public interface IThermostat  
{  
    void SetTemperature(int temperature);  
}  
  
// A smart light class implementing ILight  
public class SmartLight : ILight  
{  
    public void TurnOn()  
    {  
        Console.WriteLine("Smart light turned on");  
    }  
  
    public void TurnOff()  
    {  
        Console.WriteLine("Smart light turned off");  
    }  
}  
  
// A smart thermostat class implementing IThermostat  
public class SmartThermostat : IThermostat  
{  
    public void SetTemperature(int temperature)  
    {  
        Console.WriteLine($"Thermostat set to {temperature}°C");  
    }  
}

2、扩展和可测试性设计

接口在设计时应考虑扩展,以适应未来的更改和增强,而不会破坏现有实现。

// Interface representing a shape  
public interface IShape  
{  
    double CalculateArea();  
}  
  
// Rectangle implementation of the IShape interface  
public class Rectangle : IShape  
{  
    public double Width { get; }  
    public double Height { get; }  
    public Rectangle(double width, double height)  
    {  
        Width = width;  
        Height = height;  
    }  
    public double CalculateArea()  
    {  
        return Width \* Height;  
    }  
}  
  
// Circle implementation of the IShape interface  
public class Circle : IShape  
{  
    public double Radius { get; }  
    public Circle(double radius)  
    {  
        Radius = radius;  
    }  
    public double CalculateArea()  
    {  
        return Math.PI * Radius * Radius;  
    }  
}

在此示例中:
我们有一个 IShape 接口,它表示一个形状,并使用 CalculateArea() 方法来计算其面积。

我们有实现 IShape 接口的 Rectangle 和 Circle 形状类,每个类都提供自己特定于该形状的 CalculateArea() 方法的实现。

该设计允许通过添加实现 IShape 接口的新形状类来轻松扩展,而无需修改现有代码。例如,如果我们想为 Square 扩展它,我们可以简单地创建一个新的类 Square 使用它自己的 CalculateArea() 方法实现 IShape。

// Square implementation of the IShape interface  
public class Square : IShape  
{  
    public double SideLength { get; }  
      
    public Square(double sideLength)  
    {  
        SideLength = sideLength;  
    }  
  
    public double CalculateArea()  
    {  
        return SideLength * SideLength;  
    }  
}

不可变接口

考虑将接口设计为不可变的,这意味着一旦定义,就无法修改它们。这有助于防止意外更改并确保代码库的稳定性。

// Immutable interface representing coordinates  
public interface ICoordinates  
{  
    // Readonly properties for latitude and longitude  
    double Latitude { get; }  
    double Longitude { get; }  
}  
  
public class Coordinates : ICoordinates  
{  
    public double Latitude { get; }  
    public double Longitude { get; }  
  
    // Constructor to initialize the latitude and longitude  
    public Coordinates(double latitude, double longitude)  
    {  
        Latitude = latitude;  
        Longitude = longitude;  
    }  
}

首选组合而不是继承

在设计接口时,优先考虑组合而不是继承。这促进了代码的重用和灵活性。
// Interface representing a component that can be composed into other classes  
public interface IComponent  
{  
    void Process();  
}  
  
// Example class implementing the IComponent interface  
public class Component : IComponent  
{  
    public void Process()  
    {  
        Console.WriteLine("Performing action in Component");  
    }  
}  
  
// Example class demonstrating composition  
public class CompositeComponent  
{  
    private readonly IComponent _component;  
    public CompositeComponent(IComponent component)  
    {  
        _component = component;  
    }  
    public void Execute()  
    {  
        _component.Process();  
    }  
}

避免接口过载

具有多种方法的重载接口,仅参数的数量或类型不同,可能会导致混淆。请改用不同的方法名称或重构接口。

public interface IVehicle  
{  
    void Start();  
    void Stop();  
    void Accelerate(int speed);  
    void Accelerate(double accelerationRate);  
}

虽然类中的重载方法是一种常见的做法,但接口中的重载方法可能会导致混淆,并使类实现哪种方法变得不那么清楚。通常,最好对不同的行为使用不同的方法名称,或者在必要时将它们分隔到多个接口中

使用泛型

利用泛型创建灵活且可重用的接口,这些接口可以处理不同类型的接口。这使我们能够编写更通用的代码,并且可以处理更广泛的场景。

// Generic interface for a data access layer  
public interface IDataAccessLayer<T>  
{  
    Task<T> GetByIdAsync(int id);  
  
    Task<IEnumerable<T>> GetAllAsync();  
}

版本控制接口

当接口随时间推移而发展时,请考虑对它们进行版本控制,以保持向后兼容性,同时引入新功能。这可以通过接口继承或在接口名称中使用版本控制等技术来实现。
// Interface representing a service for processing orders  
public interface IOrderService  
{  
    Task ProcessAsync(Order order);  
}  
  
// Interface representing a service for processing orders (version 2)  
public interface IOrderServiceV2  
{  
    Task ProcessAsync(OrderV2 order);  
}

使用协变接口和逆变接口

利用 .NET 中的协方差和逆变,在处理接口实现时允许更灵活的类型转换。
// Covariant interface for reading data  
public interface IDataReader<out T>  
{  
    T ReadData();  
}  
  
// Contravariant interface for writing data  
public interface IDataWriter<in T>  
{  
    void WriteData(T data);  
}

避免脂肪界面

FAT 接口包含太多成员,这使得它们难以实现和维护。将大型接口拆分为更小、更集中的接口。
// Bad example   
  
public interface IDataRepository  
{  
    Task<Data> GetByIdAsync(int id);  
    Task AddAsync(Data data);  
    Task GenerateReportAsync();  
    Task<bool> ValidateAsync(Data data);  
} 

// Good example  
  
// Interface for data retrieval operations  
public interface IDataRepository  
{  
    Task<Data> GetByIdAsync(int id);  
    Task CreateAsync(Data data);  
}  
  
  
// Interface for data reporting operations  
public interface IDataReporting  
{  
    Task GenerateReportAsync();  
}  
  
// Interface for data validation  
public interface IDataValidation  
{  
    Task<bool> ValidateAsync(Data data);  
}

使用显式接口实现

当类实现具有相同名称的成员的多个接口时,请使用显式接口实现来消除它们的歧义。这样可以更好地控制接口成员的可见性。
public interface IInterface1  
{  
    void Method();  
}  
  
public interface IInterface2  
{  
    void Method();  
}  
  
public class MyClass : IInterface1, IInterface2  
{  
    // Explicit implementation of IInterface1.Method  
    void IInterface1.Method()  
    {  
        Console.WriteLine("IInterface1.Method");  
    }  
  
    // Explicit implementation of IInterface2.Method  
    void IInterface2.Method()  
    {  
        Console.WriteLine("IInterface2.Method");  
    }  
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/581476.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Docker | 入门:安装与配置

Docker | 入门&#xff1a;安装与配置 Docker 和传统虚拟机区别 对于传统虚拟机&#xff1a; 虚拟出一套硬件&#xff0c;运行一个完整的操作系统&#xff0c;并在这个操作系统上安装和运行软件。 对于 Docker: 将一个个容器隔离开。 容器内的应用直接运行在宿主机的内容&am…

软件模型(简洁明了)

《 软件测试基础持续更新中》 一、软件开发模型 1.1 大爆炸模型 优点&#xff1a;思路简单&#xff0c; 通常可能是开发者的“突发奇 想” 缺点&#xff1a;开发过程是非工程化的&#xff0c;随意性大&#xff0c;结果不可预知 测试&#xff1a;开发任务完成后&#xff0c;…

一个自卑的人怎么变得自信

一个自卑的人怎么变得自信 自卑感是一种常见的心理状态&#xff0c;它可能源于个人对自己能力、外貌、价值等方面的负面评价。自卑感不仅会影响一个人的情绪状态&#xff0c;还可能阻碍其在生活、学习和工作中的表现。然而&#xff0c;自信并非一蹴而就的品质&#xff0c;它需要…

基础款:Dockerfile 文件

# bash复制代码# 使用 Node.js 16 作为基础镜像 # 指定一个已经存在的镜像作为模版&#xff0c;第一条必须是from FROM node:16# 将当前工作目录设置为/app # WORKDIR /app# 方法一&#xff1a;用dockerfile命令&#xff1a;进行下载打包文件 # 将 package.json 和 package-loc…

MySQL 之 主从复制

1. 主配置文件&#xff08;win下是my.ini&#xff0c;linux下是my.cnf&#xff09; #mysql 服务ID,保证整个集群环境中唯一 server-id1 #mysql binlog 日志的存储路径和文件名 log-bin/var/lib/mysql/mysqlbin #错误日志,默认已经开启 #log-err #mysql的安装目录 #basedir #mys…

Linux软件包管理器——yum

文章目录 1.什么是软件包1.1安装与删除命令1.2注意事项1.3查看软件包1.3.1注意事项&#xff1a; 2.关于rzsz3.有趣的Linux下的指令 -sl 1.什么是软件包 在Linux下安装软件, 一个通常的办法是下载到程序的源代码, 并进行编译, 得到可执行程序. 但是这样太麻烦了, 于是有些人把一…

穷人想要改命,是选择打工还是创业? 2024创业项目小成本!2024轻资产创业!2024风口行业!2024普通人做什么行业赚钱?

今日话题穷人想要改命&#xff0c;是选择打工还是创业&#xff1f; 改命的方式就是跳进水里&#xff0c;忍受呛水&#xff0c;学会游泳&#xff0c;这个过程越年轻实现越好&#xff0c;就像小鹰往山崖下跳&#xff0c;要么学会飞&#xff0c;要么就狠狠的被摔死。打工思维和创…

用vue3实现留言板功能

效果图&#xff1a; 代码&#xff1a; <script setup lang"ts"> import { ref } from vue;interface Message {name: string;phone: string;message: string; }const name ref<string>(); const phone ref<string>(); const message ref<st…

基于YOLOV5和DeepOCSort的实时目标检测跟踪检测系统

项目简介 本项目旨在研究由YOLOV5模型在多目标检测任务重的应用。通过设计YOLOV5模型及DeepOCSORT模型来实现多物体检测、追踪&#xff0c;最终达高实时性、高精度的物件检测、分割、追踪的效果。最后通过AX620A完成嵌入式硬件部署 项目研究背景 近年来&#xff0c;近年来&am…

【Linux】fork函数详解and写时拷贝再理解

&#x1f490; &#x1f338; &#x1f337; &#x1f340; &#x1f339; &#x1f33b; &#x1f33a; &#x1f341; &#x1f343; &#x1f342; &#x1f33f; &#x1f344;&#x1f35d; &#x1f35b; &#x1f364; &#x1f4c3;个人主页 &#xff1a;阿然成长日记 …

茶叶直播间电商运营带货方案营销计划书

【干货资料持续更新&#xff0c;建议先关注&#xff0c;以防走丢】 茶叶直播间电商运营带货方案营销计划书 部分资料预览 资料部分是网络整理&#xff0c;仅供学习参考。 PPT可编辑&#xff08;完整资料包含以下内容&#xff09; 目录 直播带货方案细化 1. 直播筹划 - 目标…

基于SSM+Jsp+Mysql的汽车租赁系统的设计与实现

开发语言&#xff1a;Java框架&#xff1a;ssm技术&#xff1a;JSPJDK版本&#xff1a;JDK1.8服务器&#xff1a;tomcat7数据库&#xff1a;mysql 5.7&#xff08;一定要5.7版本&#xff09;数据库工具&#xff1a;Navicat11开发软件&#xff1a;eclipse/myeclipse/ideaMaven包…

OpenHarmony实战开发-如何实现单一手势

点击手势&#xff08;TapGesture&#xff09; TapGesture(value?:{count?:number; fingers?:number})点击手势支持单次点击和多次点击&#xff0c;拥有两个可选参数&#xff1a; count&#xff1a;声明该点击手势识别的连续点击次数。默认值为1&#xff0c;若设置小于1的非…

poi-tl自定义渲染策略学习

文章目录 实现逻辑参考代码注意点 实现逻辑 自定义渲染策略实现逻辑&#xff1a; 找到模板中的表格标签render方法接收java中对应模板表格标签的所有list数据执行自定义渲染逻辑 参考代码 word模板如下&#xff1a; 实体类&#xff1a; Data public class GksxRowData {/…

结构体枚举、联合、位段

枚举 枚举顾名思义就是一一列举。 把可能的取值一一列举。 比如我们现实生活中&#xff1a; 一周的星期一到星期日是有限的7天&#xff0c;可以一一列举。 性别有&#xff1a;男、女、保密&#xff0c;也可以一一列举。 月份有12个月&#xff0c;也可以一一列举 这里就可以使…

Shader for Quest 2: 自定义shader在Unity Editor中可以使用,但是在Quest 2中却不可以

GameObject segment GameObject.Find("DisplayArea_" i); MeshRenderer renderer segment.GetComponent<MeshRenderer>(); Material mat new Material(Shader.Find("Custom/MyShader")); mat.mainTexture option.Image360;上面这份代码&#x…

低代码开发之腾讯云微搭工具

低代码开发之腾讯云微搭工具 微搭简介诞生缘由开发模式如何创建组件模块介绍实例讲解url传参级联联动使用事件其他方法调用数据源方法 callDataSource触发流程 callProcess 引入外部css/js代码编辑器的使用Handler 方法使用介绍Style 用法示例LifeCycle 生命周期介绍 数据模型方…

【1471】java项目进度管理系统Myeclipse开发mysql数据库web结构java编程计算机网页项目

一、源码特点 java 项目进度管理系统是一套完善的java web信息管理系统&#xff0c;对理解JSP java编程开发语言有帮助&#xff0c;系统具有完整的源代码和数据库&#xff0c;系统主要采用B/S模式开发。开发环境为TOMCAT7.0,Myeclipse8.5开发&#xff0c;数据库为Mysql5.0&…

测试必备 | 测试工程师必知的Linux命令有哪些?

在日常的测试工作中&#xff0c;涉及到测试环境搭建及通过查看日志来定位相关问题时经常会用到Linux&#xff0c;在测试工程师的面试中也经常会有笔试或面试的题目来考查测试人员对Linux的熟悉程度&#xff0c;这里分享下测试工程师需知的 Linux 命令有哪些。 Linux 作为一种常…

【 书生·浦语大模型实战营】作业(四):XTuner 微调 LLM:1.8B、多模态、Agent

【 书生浦语大模型实战营】作业&#xff08;五&#xff09;&#xff1a;LMDeploy 量化部署 &#x1f389;AI学习星球推荐&#xff1a; GoAI的学习社区 知识星球是一个致力于提供《机器学习 | 深度学习 | CV | NLP | 大模型 | 多模态 | AIGC 》各个最新AI方向综述、论文等成体系…
最新文章