当前位置:网站首页>[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 Dio
class 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();
...
}
Map
The modifier defined isabstract
, Why can we instantiate through constructor ?- and
Map
Similar to thatList
, Here toMap
For example - Here
external
andfacotry
What 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
_InternalLinkedHashMap
and_CompactLinkedIdentityHashMap
object .
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 :
abstract
In an abstract classfactory
The constructor returnsinstance
example , It comes fromImplementation class
( For the time being abstract Class asinterface
,dart
It doesn't containinterface
keyword ).
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
factory
For the creation of singleton mode .
class Person {
factory Person() => _instance;
Person._internal();
static final Person _instance = Person._internal();
}
Dio
The idea in
dio
Library code Dio
Design idea .
- There are two instance object types of the factory constructor here
DioForBrowser
,DioForNative
- in order to
Mobile
andWeb side
The support of uses a more ingeniousEntrance judgment
Please 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开发学习
- [camera topic] how to save OTP data in user-defined nodes
- [fluent] fluent debugging (debug debugging window | viewing mobile phone log information | setting normal breakpoints | setting expression breakpoints)
- Rockchip3399 start auto load driver
- stm32F407-------ADC
- Reprint some Qt development experience written by great Xia 6.5
- 机器学习流程与方法
- MySQL学习03
- The Sandbox阐释对元宇宙平台的愿景
- Comment communiquer avec Huawei Cloud IOT via le Protocole mqtt
猜你喜欢
8 free, HD, copyright free video material download websites are recommended
微服务组件Sentinel (Hystrix)详细分析
《上市风云》荐书——唯勇气最可贵
[Flutter] dart: class;abstract class;factory;类、抽象类、工厂构造函数
[fluent] fluent debugging (debug debugging window | viewing mobile phone log information | setting normal breakpoints | setting expression breakpoints)
Ni visa fails after LabVIEW installs the third-party visa software
Wechat applet development tool post net:: err_ PROXY_ CONNECTION_ Failed agent problem
Performance test | script template sorting, tool sorting and result analysis
stm32F407-------DMA
[shutter] hero animation (hero realizes radial animation | hero component createrecttween setting)
随机推荐
stm32F407-------DMA
[shutter] hero animation (hero realizes radial animation | hero component createrecttween setting)
[shutter] shutter debugging (debugging control related functions | breakpoint management | code operation control)
easyExcel
微信小程序開發工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理問題
转载收录6.5大侠写的部分Qt开发经验
502 (bad gateway) causes and Solutions
Wechat applet Development Tool Post net:: Err Proxy Connexion Problèmes d'agent défectueux
缺少库while loading shared libraries: libisl.so.15: cannot open shared object file: No such file
苏世民:25条工作和生活原则
y54.第三章 Kubernetes从入门到精通 -- ingress(二七)
How to find summer technical internship in junior year? Are you looking for a large company or a small company for technical internship?
Caused by: com. fasterxml. jackson. databind. exc.MismatchedInputException: Cannot construct instance o
[leetcode] 797 and 1189 (basis of graph theory)
疫情當頭,作為Leader如何進行團隊的管理?| 社區征文
Bottleneck period must see: how can testers who have worked for 3-5 years avoid detours and break through smoothly
[Flutter] dart: class;abstract class;factory;类、抽象类、工厂构造函数
Stm32f407 ------- IIC communication protocol
[camera topic] how to save OTP data in user-defined nodes
stm32F407-------ADC