官术网_书友最值得收藏!

The observer pattern

As we advance in this book, we keep mentioning how important decoupling is. When we reduce dependencies, we can extend, develop, and test different modules without having to know the implementation details of other modules. All we have to know is the abstraction they implement.

However, modules should work together in practice. And it's not uncommon that changes in one object are known by another object. For example, if we implement a car class in a game, the engine of the car should know when the accelerator changes its position. The naive solution would be to have an engine class that checks from time to time the accelerator position to see whether it has changed. A smarter approach would be to make the accelerator call the engine to inform it about the changes. But this is not enough if we want to have well-designed code.

If the Accelerator class keeps a reference to the Engine class, what happens when we need to display on screen the position of Accelerator? This is the best solution: instead of making the accelerator dependent on the engine, we should make both of them rely on abstractions.

主站蜘蛛池模板: 兖州市| 年辖:市辖区| 诸城市| 开江县| 永胜县| 习水县| 青神县| 镇远县| 宜昌市| 绍兴县| 出国| 奇台县| 都昌县| 满洲里市| 大港区| 玛曲县| 临武县| 东阳市| 合阳县| 宁都县| 伊通| 台山市| 屏边| 遵义县| 淳安县| 霞浦县| 霍州市| 罗平县| 军事| 沙洋县| 岳普湖县| 瑞昌市| 察隅县| 昌图县| 乐陵市| 石渠县| 台东县| 太原市| 新绛县| 松原市| 美姑县|