Created
July 13, 2017 10:15
-
-
Save angelov/63c870ba7cdc6bae00c0602a85a2144a to your computer and use it in GitHub Desktop.
repository with generics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.Map.Entry; | |
public class HelloWorld | |
{ | |
public static void main(String[] args) | |
{ | |
UsersRepositoryInterface usersRepository = new UsersRepository(); | |
usersRepository.store(new User("[email protected]", "uid")); | |
User found; | |
found = usersRepository.findByEmail("[email protected]"); | |
System.out.println(found.getEmail()); | |
// Movie cannot be converted to User | |
// usersRepository.store(new Movie()); | |
} | |
} | |
interface HasId { | |
public String getId(); | |
} | |
class User implements HasId { | |
private String email; | |
private String id; | |
public User(String email, String id) { | |
this.email = email; | |
this.id = id; | |
} | |
public String getEmail() { | |
return email; | |
} | |
public String getId() | |
{ | |
return id; | |
} | |
} | |
class Movie implements HasId { | |
public String getId() { | |
return "asd"; | |
} | |
} | |
interface Repository<Entity extends HasId> { | |
public void store(Entity e); | |
public Entity find(String id) throws Exception; | |
} | |
interface UsersRepositoryInterface extends Repository<User> { | |
public User findByEmail(String email); | |
} | |
abstract class BaseRepository<Entity extends HasId> implements Repository<Entity> | |
{ | |
protected HashMap<String, Entity> storage = new HashMap<>(); | |
public void store(Entity e) { | |
storage.put(e.getId(), e); | |
} | |
public Entity find(String id) throws Exception { | |
return storage.get(id); | |
} | |
} | |
class UsersRepository extends BaseRepository<User> implements UsersRepositoryInterface { | |
public User findByEmail(String email) { | |
for (Entry<String, User> entry : storage.entrySet()) { | |
User user = entry.getValue(); | |
if (user.getEmail().equals(email)) { | |
return user; | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment