当前位置:网站首页>[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.
边栏推荐
- Missing library while loading shared libraries: libisl so. 15: cannot open shared object file: No such file
- 微信小程序開發工具 POST net::ERR_PROXY_CONNECTION_FAILED 代理問題
- 全链路数字化转型下,零售企业如何打开第二增长曲线
- Exception handling in kotlin process
- 【Camera专题】OTP数据如何保存在自定义节点中
- In the face of difficult SQL requirements, HQL is not afraid
- Recommendation letter of "listing situation" -- courage is the most valuable
- Answers to ten questions about automated testing software testers must see
- When the epidemic comes, how to manage the team as a leader| Community essay solicitation
- Analysis, use and extension of open source API gateway apisex
猜你喜欢

Stm32f407 ------- IIC communication protocol

stm32F407-------ADC

stm32F407-------DMA

Deep learning notes (constantly updating...)
![[shutter] shutter debugging (debugging fallback function | debug method of viewing variables in debugging | console information)](/img/66/0fda43da0d36fc0c9277ca86ece252.jpg)
[shutter] shutter debugging (debugging fallback function | debug method of viewing variables in debugging | console information)

Query product cases - page rendering data

Rockchip3399 start auto load driver

Asian Games countdown! AI target detection helps host the Asian Games!

udp接收队列以及多次初始化的测试

His experience in choosing a startup company or a big Internet company may give you some inspiration
随机推荐
y54.第三章 Kubernetes从入门到精通 -- ingress(二七)
【Camera专题】手把手撸一份驱动 到 点亮Camera
RestCloud ETL 跨库数据聚合运算
Asian Games countdown! AI target detection helps host the Asian Games!
Stm32f407 ------- IIC communication protocol
Socket programming
Everything file search tool
Depth (penetration) selector:: v-deep/deep/ and > > >
How do it students find short-term internships? Which is better, short-term internship or long-term internship?
udp接收队列以及多次初始化的测试
DML Foundation
2022 spring "golden three silver four" job hopping prerequisites: Software Test interview questions (with answers)
【Camera专题】Camera dtsi 完全解析
查询商品案例-页面渲染数据
File class (check)
COM和CN
Cancellation of collaboration in kotlin, side effects of cancellation and overtime tasks
Socket编程
Answers to ten questions about automated testing software testers must see
[shutter] shutter debugging (debugging fallback function | debug method of viewing variables in debugging | console information)