Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- CompositeFoo compFoo = new CompositeFoo(fooDB, fooFILE, fooLIB)
- import java.util.Collections;
- import java.util.HashSet;
- import java.util.Set;
- //interface used for composite class and data classes
- public abstract class Foo {
- abstract Set<String> getIds();
- abstract void addId(String id);
- }
- //data source from file
- class FooFromFile extends Foo {
- @Override
- Set<String> getIds() {
- //loads data from file
- }
- @Override
- void addId(String id) {
- //changes file, add there one id
- }
- }
- //data source from DB
- class FooFromDB extends Foo {
- @Override
- Set<String> getIds() {
- //loads ids from DataBase
- }
- @Override
- void addId(String id) {
- //adds id to database
- }
- }
- //class i use now, combines all Foo's
- //gets info from all, updates only main data source
- //this one i want to make generic
- class CompositeFoo extends Foo {
- private Foo mainFoo;
- private Set<Foo> others;
- public CompositeFoo(Foo mainSource, Foo ...otherSources ) {
- mainFoo = mainSource;
- others = new HashSet<>();
- Collections.addAll(others, otherSources);
- }
- @Override
- Set<String> getIds() {
- HashSet<String> result = new HashSet<>();
- //load from main source
- result.addAll(mainFoo.getIds());
- //and from other sources
- for (Foo otherFoo : others ) {
- result.addAll(otherFoo.getIds());
- }
- //ids from all the sources
- return result;
- }
- @Override
- void addId(String id) {
- //uses only main source, we don't want to add ID to all the sources
- mainFoo.addId(id);
- }
- }
- public static void main(String[] args) {
- FooFromDB dbFooMain = new FooFromDB();
- FooFromFile fileFoo = new FooFromFile();
- CompositeFoo compFoo= new CompositeFoo(dbFooMain, fileFoo);
- compFoo.add("new id"); //adds to dbFooMain only
- compFoo.getIds(); //gets from all sources (dbFooMain + fileFoo)
- }
- public static void main(String[] args) {
- FooFromDB dbFooMain = new FooFromDB();
- FooFromFile fileFoo = new FooFromFile();
- //something like this:
- MagicComposite<Foo> compFoo = new MagicComposite<>(dbFooMain, fileFoo);
- //or something like this:
- Foo compFoo = AnyCompositeFactory.createComposite(Foo.class, dbFoo, fileFoo);
- //than this should work
- //adds to dbFooMain only. dbFoo.add("new id") called
- compFoo.add("new id");
- //gets ids from all sources so dbFoo.getIds() + fileFoo.getIds() called and combined
- compFoo.getIds();
- //-----------------------------------------
- //for Bar the same magic class should do
- MagicComposite<Bar> compBar = new MagicComposite<>(dbBarMain, fileBar);
- //or
- Bar compBar = AnyCompositeFactory.createComposite(Bar.class, dbBar, fileBar);
- }
- abstract class Bar{
- @Magic(Type = retrieveInformationOnly)
- Set<String> getSomething();
- @Magic(Type = addInformation)
- void addSomething(String id);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement