两种语言实现设计模式(C++和Java)(十:外观模式)

外观模式:

为子系统中的一组接口定义一个一致的界面,外观模式提供了一个高层接口,这个接口使得这一子系统更加容易被使用;对于复杂的系统,系统为客户提供一个简单的接口,把复杂的实现过程封装起来,客户不需要了解系统内部的细节。

    主要解决:客户不需要了解系统内部复杂的细节,只需要一个接口;系统入口。
    如何解决:客户不直接与系统耦合,而是通过外观类与系统耦合。
    关键代码:客户与系统之间加一个外观层,外观层处理系统的调用关系、依赖关系等。
    缺点:需要修改时不易继承、不易修改。

 

举例:

汽车的生产需要车架,发动机,轮胎等各组件,对于用户来说这些部件均作为外观类Car的属性,用户生产车辆只需要调用外观类的接口即可,无需关心零部件的生产过程。

 

Uml:

 

C++代码实现:

 

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class FrameFactory
 6 {
 7 public:
 8     void productFrame()
 9     {
10         cout << "Product Car Frame" << endl;
11     }
12 };
13 
14 class MotorFactory
15 {
16 public:
17     void productMotor()
18     {
19         cout << "Product Car Motor" << endl;
20     }
21 };
22 
23 class WheelFactory
24 {
25 public:
26     void productWheels()
27     {
28         cout << "Product Car Wheels" << endl;
29     }
30 };
31 
32 class Car
33 {
34 private:
35     FrameFactory frameFactory;
36     MotorFactory motorFactory;
37     WheelFactory wheelFactory;
38 public:
39     void getCar()
40     {
41         frameFactory.productFrame();
42         motorFactory.productMotor();
43         wheelFactory.productWheels();
44         cout << "Product a car" << endl;
45     }
46 };
47 
48 int main()
49 {
50     Car car;
51     car.getCar();
52     return 0;
53 }

 

 

 

Java代码实现:

 

 1 public class FrameFactory {
 2 
 3     public void productFrame(){
 4         System.out.println("Product CarFactory Frame");
 5     }
 6 }
 7 
 8 public class MotorFactory {
 9 
10     public void productMotor(){
11         System.out.println("Product motor");
12     }
13 }
14 
15 public class WheelFactory {
16 
17     public void productWheels(){
18         System.out.println("Product Wheels");
19     }
20 }
21 
22 public class CarFactory {
23 
24     private FrameFactory frameFactory;
25 
26     private MotorFactory motorFactory;
27 
28     private WheelFactory wheelFactory;
29 
30     public CarFactory(){
31         frameFactory = new FrameFactory();
32         motorFactory = new MotorFactory();
33         wheelFactory = new WheelFactory();
34     }
35 
36     public void getCar(){
37         frameFactory.productFrame();
38         motorFactory.productMotor();
39         wheelFactory.productWheels();
40         System.out.println("Product a car");
41     }
42 
43 }
44 
45 public class Main {
46 
47     public static void main(String[] args) {
48         CarFactory carFactory = new CarFactory();
49         carFactory.getCar();
50     }
51 
52 }

 

转载于:https://www.cnblogs.com/Asp1rant/p/11160251.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值