handle class和interface class

本文介绍了两种降低文件间依赖的方法:handleclass 和 interfaceclass。handleclass 方法通过将类分解为接口类和实现类来减少直接依赖,而 interfaceclass 方法则通过创建抽象基类和具体实现类来达到同样的目的。

降低文件间的依存关系:
第一种方法: handle class
把一个类变为一个接口类和一个实现类 实现类就是原来的这个类,接口类就是原来这个类的接口函数(public)和 一个private的智能指针对象(一般为shared_ptr)指向实现类,接口类里面需要用到的类,我们提供给它的都是类的前向声明,所以为了严格执行这样的准则,我们把每一个类(包括接口类和实现类)都提供两个头文件,一个是类的声明 xxfwd.h 一个是类的定义 xx.h 


接口类的fwd.h   class xx fwd.;
接口类的头文件  include的都是 xxfwd.h   就是接口类需要用到的类的fwd.h 和实现类的 fwd.h
接口类的源文件  include 自己的头文件和实现类的头文件 接口函数的实现通过实现类的接口函数实现

实现类的fwd.h   class xximplfwd; 
实现类的头文件  include 用到的类的 接口类 的头文件 
实现类的源文件  include  实现类的头文件
 

// file : Person.h 原来的
#include <string>
#include "date.h"
#include "address.h"

class Person{
    public:
    Person( const std::string& name, const Date& birthday, const Address& addr );
    std::string name() const;
    std::string birthData() const;
    std::string address() const;
    ...
    private:
    std::string theName;
    Date theBirthDate;
    Address theAddress;
}

// Personfwd.h
class Person;

// datefwd.h
class date;

//Person.h
#include <string>
#include <memory.h>
#include "datefwd.h"
#include "addressfwd.h"
#include "PersonImplfwd.h"
class Person{
    public:
    Person( const std::string& name, const Date& birthday, const Address& addr );
    std::string name() const;
    std::string birthData() const;
    std::string address() const;
    ...
    private:
    std::shared_ptr<PersonImpl> pImpl; // 指针指向实现物
}

//PersonImpl.h  有着和Person完全相同的成员函数,两者接口完全相同。
#include "date.h"
#include "address.h"
class PersonImpl
{
    public:
    PersonImpl( const std::string& name, const Date& birthday, const Address& addr );
    std::string name() const;
    std::string birthData() const;
    std::string address() const;
    ...
    private:
    std::string theName;
    Date theBirthDate;
    Address theAddress;
}

//Person.cpp
#include "Person.h"
#include "PersonImpl.h"
std::string Person::name() const{
    return pImpl->name();
}
...
...

//PersonImpl.cpp
#include "PersonImpl.h"
std::string PersonImpl::name() const {
    return theName;
}
...
...

优点

  • Person.h 实现了与之前依赖的头文件 date.h 和 address.h 及由此递归依赖的文件的解耦,可是改为 PersonImpl.h依赖上述文件,只是该依赖不会继续向上传递;
  • Person 类型的声明 Person.h 及实现 PersonImpl.h 的解耦, 修改 Person 类实现时,只需要修改 PersonImpl.h 即可,不会影响使用 Person 类的文件。

代价

  • 成员函数必须通过 implemention pointer 取得对象数据,访问是间接的,且增加了 implemetion pointer 的指针的内存,增加了动态内存分配的管理开销,及 bad_alloc 异常的处理难度。

 

第二种方法: interface class 
原来一个A类,让它的接口成为一个抽象基类 class A,具体是 接口函数都定义成为 纯虚函数,  析构函数是虚函数,还有一个static工厂函数 create 返回shared_ptr<A> 
它的实现成为派生类  Aimpl,这样改变A类的实现,就改变Aimpl的实现就ok了
客户用的时候只能  shared_ptr<A>  Aptr(A::create(参数) ) ; 这样用



 

<think>好的,我需要回答用户关于PHP中traitinterface的区别及使用场景的问题。首先,我需要回忆一下PHP中的traitinterface的基本概念。 根据用户提供的引用内容,interface使用关键字interface定义,类通过implements实现接口,必须实现所有方法。例如,User接口有两个方法,VipUser类实现了它们。接口主要用于定义规范,确保实现类有特定的方法。 而trait则是用关键字trait定义,用于代码复用。因为PHP是单继承,trait允许在不继承另一个类的情况下复用方法。例如,引用[2][3]提到trait解决单继承限制,可以在不同类中复用方法。比如,如果有多个类需要同样的方法,可以用trait来包含这些方法,避免重复代码。 接下来,我需要比较它们的区别。接口是定义方法签名,要求实现类必须实现这些方法,属于一种契约。而trait是提供具体的方法实现,直接注入到类中,不需要再实现。接口关注于“能做什么”,而trait关注于“有什么功能”。 使用场景方面,接口适合定义统一的行为规范,比如不同的用户类型都需要有getDiscount方法,那么用接口确保一致性。而trait适合多个不相关的类需要共享相同的方法,比如日志功能或工具方法,可以在多个类中使用同一个trait,避免代码重复。 还要注意接口可以实现多个,但trait可以组合多个,但使用时可能会有冲突,需要解决冲突。比如引用[3]提到trait组合时可能出现方法名冲突,需要用insteadof或as来调整。 需要确保回答结构清晰,分点说明区别使用场景,并给出示例,符合用户提供的引用内容。同时检查是否有遗漏点,比如finalabstract的区别,但用户问题只关注traitinterface,所以不需要涉及其他概念。 最后,生成相关问题,可能需要包括trait与抽象类的区别,如何解决trait冲突,接口的应用场景等。确保问题相关且有参考价值。</think>### PHP中Trait与Interface的区别及使用场景分析 #### 一、核心区别对比 1. **定义方式与语法** - **Interface**:通过`interface`关键字定义,仅包含方法签名(无具体实现)。例如: ```php interface Logger { public function log($message); } ``` - **Trait**:通过`trait`关键字定义,包含具体方法实现。例如: ```php trait FileLogger { public function log($message) { file_put_contents('log.txt', $message, FILE_APPEND); } } ``` 2. **实现方式** - **Interface**:类必须通过`implements`显式实现接口,并强制定义所有方法[^1]。 ```php class UserLogger implements Logger { public function log($message) { // 必须实现 } } ``` - **Trait**:通过`use`关键字将方法注入类中,无需重复编写代码[^2]。 ```php class OrderService { use FileLogger; // 直接获得log方法 } ``` 3. **设计目标** - **Interface**:定义**行为规范**,强调"能做什么"(如用户类型必须支持折扣计算)[^1]。 - **Trait**:实现**代码复用**,解决单继承限制,提供"现成功能"(如日志、缓存等工具方法)[^3]。 #### 二、使用场景对比 | 特性 | Interface | Trait | |---------------------|-------------------------------------|--------------------------------| | **多态支持** | ✅ 通过类型约束实现 | ❌ 无法单独类型约束 | | **代码复用** | ❌ 仅定义规范 | ✅ 直接注入实现 | | **多继承模拟** | ✅ 类可实现多个接口 | ✅ 类可组合多个trait | | **版本兼容性** | ✅ 所有PHP版本支持 | ✅ PHP 5.4+ 支持 | **典型场景示例:** 1. **Interface适用场景** 当需要统一不同类的方法调用标准时,例如支付网关集成: ```php interface PaymentGateway { public function charge($amount); } class StripeGateway implements PaymentGateway { public function charge($amount) { /* Stripe逻辑 */ } } class PayPalGateway implements PaymentGateway { public function charge($amount) { /* PayPal逻辑 */ } } ``` 2. **Trait适用场景** 当多个无关类需要共享相同功能时,例如添加日志功能: ```php trait RequestTracer { protected function logRequest() { // 记录请求信息的通用实现 } } class ApiController { use RequestTracer; public function handle() { $this->logRequest(); } } class BatchJob { use RequestTracer; public function run() { $this->logRequest(); } } ``` #### 三、组合使用技巧 二者可协同工作,例如通过接口定义规范,用trait提供默认实现: ```php interface Cacheable { public function getCacheKey(); } trait RedisCache { public function cache($data) { $key = $this->getCacheKey(); // 依赖接口方法 Redis::set($key, $data); } } class ProductRepository implements Cacheable { use RedisCache; public function getCacheKey() { return 'product_' . $this->id; } } ``` 此模式强制实现类定义`getCacheKey()`,同时复用缓存逻辑[^3]。 #### 四、冲突处理 当多个trait包含同名方法时,需使用`insteadof``as`解决冲突: ```php trait FormatterA { public function format() { /* A逻辑 */ } } trait FormatterB { public function format() { /* B逻辑 */ } } class Report { use FormatterA, FormatterB { FormatterA::format insteadof FormatterB; FormatterB::format as formatRaw; } } ``` 此时`format()`使用FormatterA的实现,FormatterB的实现可通过`formatRaw()`调用[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值