- Scala Functional Programming Patterns
- Atul S. Khot
- 301字
- 2021-07-30 09:44:23
Chapter 2. Singletons, Factories, and Builders
It may sound funny—and I may be stating the obvious—but everyone needs to be born at some point. Go ahead and have a good laugh at that. It is that obvious. Objects, too, need to be born at some point to do useful work. Objects have a lifetime as well. An object is constructed—and hopefully it does something useful before it eventually dies.
In Java we can see the object such as:
Point p = new Point(23, 94);
We know what is going on—an object of class point is created; its constructor-invoked p
is a reference to this newly created object.
At times, we want explicit control of the object-creation process. There are times when we want to allow creation of only one instance of a class. Creational design patterns deal with object-creation mechanisms. Refer to https://sourcemaking.com/design_patterns/creational_patterns for more information on creational patterns.
Creational patterns help create objects in a manner suitable to the situation. Some expensive objects may need to be lazy-initialized. Refer to http://martinfowler.com/bliki/LazyInitialization.html for a very nice introduction to lazy initialization.
Scala provides some nifty ways for lazy initialization, as we will soon see.
We will first look at singletons and then Null Object, a specialized singleton, to avoid null checks. We will use our understanding to implement a set of numbers as a Binary Search Tree (BST). Scala Options are an alternative to null check-based programming. We will rewrite the set implementation in Scala using Options. We will also look at how singletons work in Scala and related idioms.
The next pattern we will look at is factories. We will look at the Java version first and redo the solution in Scala. We will look at some related Scala idioms too.
- Reporting with Visual Studio and Crystal Reports
- Cocos2d-x游戲開發:手把手教你Lua語言的編程方法
- Elastic Stack應用寶典
- 人人都懂設計模式:從生活中領悟設計模式(Python實現)
- 數據結構案例教程(C/C++版)
- Beginning C++ Game Programming
- Qlik Sense? Cookbook
- 玩轉.NET Micro Framework移植:基于STM32F10x處理器
- 算法設計與分析:基于C++編程語言的描述
- Visual Basic程序設計實驗指導及考試指南
- Java編程指南:語法基礎、面向對象、函數式編程與項目實戰
- Distributed Computing with Python
- 趣學數據結構
- Java EE互聯網輕量級框架整合開發:SSM+Redis+Spring微服務(上下冊)
- Pandas入門與實戰應用:基于Python的數據分析與處理