Reputation: 815
I want to set up a mixin with standard persistence behavior. The mixin looks like that:
mixin Persistence<T> {
static late final PersistenceBase persistence;
static void add(T object) {
persistence.add(object);
}
static void delete(T object) {
persistence.delete(object);
}
static T elementAt(int index) => persistence.elementAt(index);
static Iterable<T> getAll() => persistence.getAll();
static T get first => persistence.getFirst();
static T get last => persistence.getLast();
static int get length => persistence.getLength();
}
Usage of persistence would look like that:
class A with Persistence {
String var1;
int var2;
}
A.add(A("test", 1));
var length = A.getLength();
A firstElement = A.getFirst();
However Dart doesn't allow using generics with static methods:
Static members can't reference type parameters of the class. Try removing the reference to the type parameter, or making the member an instance member
The point is that I don't want to create instance of A
class just to access persistence functionality for the class.
So far I have done this way:
class PersistenceManager<T> {
late final PersistenceBase persistence;
void add(T object) {
persistence.add(object);
}
void delete(T object) {
persistence.delete(object);
}
T elementAt(int index) => persistence.elementAt(index);
Iterable<T> getAll() => persistence.getAll();
T get first => persistence.getFirst();
T get last => persistence.getLast();
int get length => persistence.getLength();
}
class Asset {
static final persistenceMgr = PersistenceManager<Asset>();
...
}
Asset.persistenceMgr.add(Asset());
That though requires adding mandatory static field for each class that would use persistence.
Is there other more elegant solution?
Upvotes: 1
Views: 134
Reputation: 71763
This is not going to work.
Dart mixin application works by mixing in the instance members of the mixin, and doing nothing to the static members.
You won't be able to do A.elementAt(...)
with or without generics, because the A
class doesn't have any static elementAt
method. The Persistance
mixin has one, but you have to call it as Persistance.elementAt
. It's not the same namespace as A
, and there is no inheritance, or mixin-in, of static members.
If you want a PersistanceBase
per class, you do need to declare it yourself, and putting the methods which operate on the base onto the same per-class value seems like the optimal design.
So, no, there is no other more elegant solution. What you have is elegant.
Upvotes: 1