当前位置:网站首页>[Flutter] dart: class; abstract class; factory; Class, abstract class, factory constructor
[Flutter] dart: class; abstract class; factory; Class, abstract class, factory constructor
2022-07-03 02:10:00 【github_ thirty-four million five hundred and fifty-two thousand】
One 、 origin
JJ Recently in use Flutter Before refactoring Native Project time , For Network Library dio When packaging, I found Dio In the instance, it is Dio Object time , I found out by accident that Dioclass Abstract class , But it can be used Dio() Constructor instantiation , Why is that ? see Flutter Source code collection objects List, Map It is defined as abstract class shock !!! why?
From the factory Factory constructor .
Two 、 About dart in class Statement of
1. Take up a
Example adoption Official documents And document description , Due to documents and blog A number of , No more details here .
class Logger {
final String name;
bool mute = false;
static final Map<String, Logger> _cache = <String, Logger>{};
factory Logger(String name) {
return _cache.putIfAbsent(name, () => Logger._internal(name));
}
factory Logger.fromJson(Map<String, Object> json) {
return Logger(json['name'].toString());
}
Logger._internal(this.name);
void log(String msg) {
if (!mute) print(msg);
}
}
The above code appears factory It will be described below
3、 ... and 、abstract class abstract class
3.1 dart Abstract classes in cannot be instantiated ?
The answer is yes , Like other languages, abstract classes cannot be instantiated .
How to explain the following code ?
Map<String, dynamic> map = Map();
Track down Map The definition of
// from: DartPackage/sky_engine/core/main.dart
...
/// Creates an empty [LinkedHashMap].
abstract class Map<K, V> {
external factory Map();
...
}
MapThe modifier defined isabstract, Why can we instantiate through constructor ?- and
MapSimilar to thatList, Here toMapFor example - Here
externalandfacotryWhat do you mean , Is it their influence ? Follow this clue to find out .
3.2 warren
3.2.1 external
9.4 External Functions externalFunctions
An external function is a function whose body is provided separately from its
declaration. An external function may be a top-level function (19), a method
(10.2, 10.8), a getter (10.3), a setter (10.4), or a non-redirecting constructor
(10.7.1, 10.7.2). External functions are introduced via the built-in identifier
external (17.38) followed by the function signature.
Document index
JJ The understanding of the :external: Compile identity , The main function of keywords is : Separate declaration from implementation .external Function may be a top-level function , Or the method , Or a getter, One setter Or, Non redirected constructor . Balabala so much , Indicates that the keyword Is used to define Statement Of . Later, it mainly explains , It's for solving dart.vm It is introduced in the different implementation of browser, client and server platforms . This is nonsense again , Um. , Let's follow this clue to find this Map Of body( Realization )!
3.2.1 body
According to the clue , We know ,Map() Created a /// Creates an empty [LinkedHashMap]. And then we start with LinkedHashMap Starting with , There are also documents about dart.vm To the , So I can only go and have a look sdk 了 .IDE open sdk Global search .

Fortunately, the search results are not many , Just look at it one by one , Go to the first file first . Limited space , Only snippets of code are intercepted ,
@patch
class LinkedHashMap<K, V> {
@patch
factory LinkedHashMap(
...
if (isValidKey == null) {
if (hashCode == null) {
if (equals == null) {
return new _InternalLinkedHashMap<K, V>();
}
hashCode = _defaultHashCode;
} else {
if (identical(identityHashCode, hashCode) &&
identical(identical, equals)) {
return new _CompactLinkedIdentityHashMap<K, V>();
}
...
- Here we know ,LinkedHashMap It's back
_InternalLinkedHashMapand_CompactLinkedIdentityHashMapobject .
3.2.2 @Path What is it ?
path The main function of is and external Associated annotations .
3.2.3 The final search scope is narrowed down to the above two objects
The catalogue is ur flutter sdk path/bin/cache/dart-sdk/lib/_internal/vm/bin/compact_hash.dart
// VM-internalized implementation of a default-constructed LinkedHashMap.
@pragma("vm:entry-point")
class _InternalLinkedHashMap<K, V> extends _HashVMBase
with
MapMixin<K, V>,
_HashBase,
_OperatorEqualsAndHashCode,
_LinkedHashMapMixin<K, V>
implements LinkedHashMap<K, V> {
_InternalLinkedHashMap() {
_index = _uninitializedIndex;
_hashMask = _HashBase._UNINITIALIZED_HASH_MASK;
_data = _uninitializedData;
_usedData = 0;
_deletedKeys = 0;
}
- It can be explained that :
abstractIn an abstract classfactoryThe constructor returnsinstanceexample , It comes fromImplementation class( For the time being abstract Class asinterface,dartIt doesn't containinterfacekeyword ).
3.2.4 _CompactLinkedIdentityHashMap
The process of exploration is the same .
3.3 summary
3.3.1 Reason for instantiation of abstract class real constructor
Because of abstract classes factory The role of factory constructors , Returns an instance of the implementation class instance .
Official documents describe :factory Constructor returns instance Not all instances are created from this implementation class , It may come from the cache , That is, what is shown in Chapter 2 ; It may also come from subclasses .
3.3.2 Scenarios to be studied
factoryFor the creation of singleton mode .
class Person {
factory Person() => _instance;
Person._internal();
static final Person _instance = Person._internal();
}
DioThe idea in
dio Library code Dio Design idea .
- There are two instance object types of the factory constructor here
DioForBrowser,DioForNative - in order to
MobileandWeb sideThe support of uses a more ingeniousEntrance judgmentPlease refer to the notes section for details - The instantiation of multi terminal support comes from this dart-clang-issue;
...
// Entry judgment code
import 'entry_stub.dart'
if (dart.library.html) 'entry/dio_for_browser.dart'
if (dart.library.io) 'entry/dio_for_native.dart';
abstract class Dio {
factory Dio([BaseOptions? options]) => createDio(options);
....
}
logs
- jeversonjee 22.07.02 3.3.4.
边栏推荐
- The testing process that software testers should know
- Leetcode(540)——有序数组中的单一元素
- 各国Web3现状与未来
- Distributed transaction solution
- Network security - phishing
- Caused by: com. fasterxml. jackson. databind. exc.MismatchedInputException: Cannot construct instance o
- 《上市风云》荐书——唯勇气最可贵
- How to refresh the opening amount of Oracle ERP
- 详细些介绍如何通过MQTT协议和华为云物联网进行通信
- [shutter] shutter debugging (debugging control related functions | breakpoint management | code operation control)
猜你喜欢

8 free, HD, copyright free video material download websites are recommended

RestCloud ETL 跨库数据聚合运算

创建+注册 子应用_定义路由,全局路由与子路由

Huakaiyun (Zhiyin) | virtual host: what is a virtual host

返回一个树形结构数据

easyPOI

How do it students find short-term internships? Which is better, short-term internship or long-term internship?

Hard core observation 547 large neural network may be beginning to become aware?

Deep learning notes (constantly updating...)

Custom components, using NPM packages, global data sharing, subcontracting
随机推荐
ByteDance data Lake integration practice based on Hudi
A 30-year-old software tester, who has been unemployed for 4 months, is confused and doesn't know what to do?
In the face of difficult SQL requirements, HQL is not afraid
How to deal with cache hot key in redis
Wechat applet development tool post net:: err_ PROXY_ CONNECTION_ Failed agent problem
Network security - password cracking
[shutter] hero animation (hero realizes radial animation | hero component createrecttween setting)
全链路数字化转型下,零售企业如何打开第二增长曲线
[Yu Yue education] reference materials of chemical experiment safety knowledge of University of science and technology of China
[shutter] shutter debugging (debugging fallback function | debug method of viewing variables in debugging | console information)
Missing library while loading shared libraries: libisl so. 15: cannot open shared object file: No such file
Redis:Redis的简单使用
Su Shimin: 25 principles of work and life
Redis: simple use of redis
How to refresh the opening amount of Oracle ERP
Distributed transaction solution
可视化yolov5格式数据集(labelme json文件)
返回一个树形结构数据
浏览器是如何对页面进行渲染的呢?
502 (bad gateway) causes and Solutions