两种语言实现设计模式(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 }

 

posted @ 2019-07-09 20:26  Asp1rant  阅读(209)  评论(0编辑  收藏  举报