0

I'm currently developing a website with dart replacing JavaScript. I want to have some code hidden for the average user, and some other code visible for users logged in. My idea was to have (at least) two dart files both with main() functions, one visible and one hidden to the average user. Now I have a class with a factory returning a cached instance. However this instance is not cached from file to file. How do I get the same instance in two different dart files?

EDIT: Code example

File file1.dart

import "some_lib.dart";

main(){
    var a = new A("string1");
    print(a.string);
}

File file2.dart

import "some_lib.dart";

main(){
    var a = new A("string2");
    print(a.string);
}

File some_lib.dart

library some_lib;

class A{
    String string;
    static A _cached;

    factory A(String s){
        if(_cached == null){
            _cached = new A._internal(s);
        }
        return _cached;
    }

    A._internal(this.string);

}

File index.html

<!DOCTYPE html>
<html>
    <head>
        <script type="application/dart" src="file1.dart"></script>
        <script type="application/dart" src="file2.dart"></script>
        <script type="text/javascript" src="packages/browser/dart.js"></script>
    </head>
    <body>
        <h1>THIS IS DARTA</h1>
    </body>
</html>

I expect this to print

string1
string1

in the console, but I get

string1
string2
4

1 回答 1

2

两个独立的程序不能相互影响(通过文件和套接字等 IO 操作除外)。

从我所见,您正在使用两个不同的程序执行两次虚拟机。他们的库将完全独立。想象一下,一个具有全局状态的重要库(例如您提到的惰性工厂构造函数)存储在系统目录中。如果没有为每个程序复制库,则完全独立的程序会相互干扰。

另一种看待它的方式:VM 为每个程序创建一个新的(隐式)隔离。程序有自己的副本和内存。即使在同一个程序中,您也只能通过消息传递在两个隔离之间进行通信(其中每条消息都被序列化和反序列化)。两个隔离区也会有不同的缓存工厂构造函数。

于 2013-05-06T19:42:23.377 回答