当前位置:网站首页>[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.
边栏推荐
- Network security - phishing
- Detailed introduction to the deployment and usage of the Nacos registry
- Rockchip3399 start auto load driver
- Comment le chef de file gère - t - il l'équipe en cas d'épidémie? Contributions communautaires
- Visual yolov5 format data set (labelme JSON file)
- Query product cases - page rendering data
- 可视化yolov5格式数据集(labelme json文件)
- Hard core observation 547 large neural network may be beginning to become aware?
- Huakaiyun | virtual host: IP, subnet mask, gateway, default gateway
- File class (add / delete)
猜你喜欢

The technology boss is ready, and the topic of position C is up to you

stm32F407-------ADC
![[shutter] top navigation bar implementation (scaffold | defaulttabcontroller | tabbar | tab | tabbarview)](/img/f1/b17631639cb4f0f58007b86476bcc2.gif)
[shutter] top navigation bar implementation (scaffold | defaulttabcontroller | tabbar | tab | tabbarview)

微服务组件Sentinel (Hystrix)详细分析

深度学习笔记(持续更新中。。。)

Bottleneck period must see: how can testers who have worked for 3-5 years avoid detours and break through smoothly

Introduce in detail how to communicate with Huawei cloud IOT through mqtt protocol

stm32F407-------ADC

Technology sharing | Frida's powerful ability to realize hook functions
![[fluent] hero animation (hero animation use process | create hero animation core components | create source page | create destination page | page Jump)](/img/68/65b8c0530cfdc92ba4f583b0162544.gif)
[fluent] hero animation (hero animation use process | create hero animation core components | create source page | create destination page | page Jump)
随机推荐
Performance test | script template sorting, tool sorting and result analysis
Asian Games countdown! AI target detection helps host the Asian Games!
Wechat applet development tool post net:: err_ PROXY_ CONNECTION_ Failed agent problem
Summary of ES6 filter() array filtering methods
Machine learning notes (constantly updating...)
Trial setup and use of idea GoLand development tool
[camera special topic] Hal layer - brief analysis of addchannel and startchannel
File class (add / delete)
人脸识别6- face_recognition_py-基于OpenCV使用Haar级联与dlib库进行人脸检测及实时跟踪
Query product cases - page rendering data
返回一个树形结构数据
微服务组件Sentinel (Hystrix)详细分析
【Camera专题】Camera dtsi 完全解析
Swift development learning
苏世民:25条工作和生活原则
Use go language to realize try{}catch{}finally
In 2022, 95% of the three most common misunderstandings in software testing were recruited. Are you that 5%?
Cfdiv2 fixed point guessing- (interval answer two points)
CFdiv2-Fixed Point Guessing-(区间答案二分)
使用Go语言实现try{}catch{}finally