当前位置:网站首页>[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.
边栏推荐
- Swift开发学习
- 使用Go语言实现try{}catch{}finally
- [shutter] shutter debugging (debugging control related functions | breakpoint management | code operation control)
- Huakaiyun (Zhiyin) | virtual host: what is a virtual host
- Hard core observation 547 large neural network may be beginning to become aware?
- elastic stack
- 单词单词单词
- 去除网页滚动条方法以及内外边距
- [Yu Yue education] China Ocean University job search OMG reference
- 力扣(LeetCode)183. 从不订购的客户(2022.07.02)
猜你喜欢
![[shutter] shutter debugging (debugging control related functions | breakpoint management | code operation control)](/img/fe/c053f8d116eb307733177283a26318.png)
[shutter] shutter debugging (debugging control related functions | breakpoint management | code operation control)

elastic stack

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

Y54. Chapter III kubernetes from introduction to mastery -- ingress (27)

Rockchip3399 start auto load driver

SPI机制

What are the differences between software testers with a monthly salary of 7K and 25K? Leaders look up to you when they master it

Query product cases - page rendering data

easyExcel

Processing of tree structure data
随机推荐
Internal connection query and external connection
[shutter] pull the navigation bar sideways (drawer component | pageview component)
DQL basic operation
通达OA 首页门户工作台
CFdiv2-Fixed Point Guessing-(區間答案二分)
Reprint some Qt development experience written by great Xia 6.5
The Sandbox阐释对元宇宙平台的愿景
How to deal with cache hot key in redis
How to find summer technical internship in junior year? Are you looking for a large company or a small company for technical internship?
Learn BeanShell before you dare to say you know JMeter
Return the only different value (de duplication)
Analysis, use and extension of open source API gateway apisex
COM和CN
File class (check)
easyPOI
Job object of collaboration in kotlin
疫情当头,作为Leader如何进行团队的管理?| 社区征文
Network security - password cracking
Qt之QComboBox添加QCheckBox(下拉列表框插入复选框,含源码+注释)
[shutter] shutter debugging (debugging control related functions | breakpoint management | code operation control)