有35mm接口及25mm接口; USB Type-C接口;lighting接口分别用类模式和对象模式实现耳机接口的转换写出代码C++
类模式实现:
class Earphone { public: virtual void play() = 0; };
class ThreePointFiveEarphone : public Earphone { public: void play() { cout << "Playing music with a 3.5mm earphone." << endl; } };
class TwoPointFiveEarphone : public Earphone { public: void play() { cout << "Playing music with a 2.5mm earphone." << endl; } };
class UsbTypeCEarphone : public Earphone { public: void play() { cout << "Playing music with a USB Type-C earphone." << endl; } };
class LightingEarphone : public Earphone { public: void play() { cout << "Playing music with a Lighting earphone." << endl; } };
class EarphoneAdapter { public: virtual Earphone* convert() = 0; };
class ThreePointFiveToUsbTypeCAdapter : public EarphoneAdapter { public: Earphone* convert() { return new UsbTypeCEarphone(); } };
class TwoPointFiveToUsbTypeCAdapter : public EarphoneAdapter { public: Earphone* convert() { return new UsbTypeCEarphone(); } };
class ThreePointFiveToLightingAdapter : public EarphoneAdapter { public: Earphone* convert() { return new LightingEarphone(); } };
class TwoPointFiveToLightingAdapter : public EarphoneAdapter { public: Earphone* convert() { return new LightingEarphone(); } };
// 使用示例 EarphoneAdapter* adapter = new ThreePointFiveToUsbTypeCAdapter(); Earphone* earphone = adapter->convert(); earphone->play();
对象模式实现:
class Earphone { public: virtual void play() = 0; };
class ThreePointFiveEarphone : public Earphone { public: void play() { cout << "Playing music with a 3.5mm earphone." << endl; } };
class TwoPointFiveEarphone : public Earphone { public: void play() { cout << "Playing music with a 2.5mm earphone." << endl; } };
class UsbTypeCEarphone : public Earphone { public: void play() { cout << "Playing music with a USB Type-C earphone." << endl; } };
class LightingEarphone : public Earphone { public: void play() { cout << "Playing music with a Lighting earphone." << endl; } };
class EarphoneAdapter { public: virtual Earphone* convert() = 0; };
class ThreePointFiveToUsbTypeCAdapter : public EarphoneAdapter { public: Earphone* convert() { return new UsbTypeCEarphone(); } };
class TwoPointFiveToUsbTypeCAdapter : public EarphoneAdapter { public: Earphone* convert() { return new UsbTypeCEarphone(); } };
class ThreePointFiveToLightingAdapter : public EarphoneAdapter { public: Earphone* convert() { return new LightingEarphone(); } };
class TwoPointFiveToLightingAdapter : public EarphoneAdapter { public: Earphone* convert() { return new LightingEarphone(); } };
// 使用示例 Earphone* earphone = new ThreePointFiveEarphone(); EarphoneAdapter* adapter = new ThreePointFiveToUsbTypeCAdapter(); earphone = adapter->convert(); earphone->play()
原文地址: https://www.cveoy.top/t/topic/hjla 著作权归作者所有。请勿转载和采集!