Basic examples of using mixins and typedefs in Dart
Find this at dartpad.dartlang.org/adb3ebb1f08c692eea5f30018b5cd046.
Basic examples of using mixins and typedefs in Dart
Find this at dartpad.dartlang.org/adb3ebb1f08c692eea5f30018b5cd046.
d(id) => new Document(id.toString()); //convenience function | |
List<Document> docs = [d('Foo'), d('bar'), d('BIZ'), d('Baz'), d('fab')]; | |
///A simple document class with id | |
class Document { | |
String id; | |
Document(this.id); | |
toString() => id; | |
} | |
///Any function that meets this signature is a Matcher | |
typedef bool Matcher(String s, Document d); | |
abstract class AbstractDocumentRepo { | |
///The store of documents | |
List<Document> _repo; | |
AbstractDocumentRepo(this._repo); | |
///Search the documents, returning a list of matched docs | |
List<Document> search(String term) => _repo.where( (doc) => matcher(term, doc)); | |
///A matching strategy for documents | |
Matcher get matcher; | |
} | |
class CaseSensitiveMatchingBehavior { | |
Matcher get matcher => (String s, Document d) => d.id.contains(s); | |
} | |
class CaseInsensitiveMatchingBehavior { | |
Matcher get matcher => (String s, Document d) => d.id.toLowerCase().contains(s.toLowerCase()); | |
} | |
class SensitiveDocRepo extends AbstractDocumentRepo with CaseSensitiveMatchingBehavior { | |
SensitiveDocRepo(r): super(r); | |
} | |
class InsensitiveDocRepo extends AbstractDocumentRepo with CaseInsensitiveMatchingBehavior { | |
InsensitiveDocRepo(r): super(r); | |
} | |
class CustomDocRepo extends AbstractDocumentRepo { | |
CustomDocRepo(r): super(r); | |
Matcher get matcher => (String s, Document d) => d.id == s; | |
} | |
main() async { | |
print(" * Starting *"); | |
AbstractDocumentRepo r1 = new SensitiveDocRepo(docs); | |
AbstractDocumentRepo r2 = new InsensitiveDocRepo(docs); | |
AbstractDocumentRepo r3 = new CustomDocRepo(docs); | |
print(r1.search("B")); | |
print(r2.search("B")); | |
print(r3.search("Baz")); | |
print("Is r1 case sensitive? ${r1 is CaseSensitiveMatchingBehavior}"); | |
print("Is r1 case insensitive? ${r1 is CaseInsensitiveMatchingBehavior}"); | |
print("Is r1.matcher a matcher? ${r1.matcher is Matcher}"); | |
Function f = (String s, Document d) => false; | |
print("Is f a matcher? ${f is Matcher}"); | |
Function g = (String s) => false; | |
print("Is g a matcher? ${g is Matcher}"); | |
Function h = (String s, Document d) => s; | |
print("Is h a matcher? ${h is Matcher}"); | |
print(" * Ending * "); | |
} |