Last active
February 27, 2018 09:23
-
-
Save uzimith/bfd3fa494cff95a1df815c70cce81e62 to your computer and use it in GitHub Desktop.
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
fn main() { | |
let user_dao = UserMockDao {}; | |
let post_dao = PostMockDao {}; | |
let app = App { user_dao, post_dao }; | |
println!("{:?}", app.get_user_by_id(2)); | |
app.show_by_id(1); | |
app.show_by_id(2) | |
} | |
pub type Result<T> = std::result::Result<T, Box<std::error::Error>>; | |
#[derive(Debug)] | |
pub struct User { | |
id: i32, | |
} | |
#[derive(Debug)] | |
pub struct Post { | |
id: i32, | |
} | |
pub trait UserDao { | |
fn find_user(&self, id: i32) -> Result<Option<User>>; | |
} | |
pub trait HaveUserDao { | |
type UserDao: UserDao; | |
fn user_dao(&self) -> &Self::UserDao; | |
} | |
struct UserMockDao(); | |
impl UserDao for UserMockDao { | |
fn find_user(&self, id: i32) -> Result<Option<User>> { | |
Ok(Some(User { id })) | |
} | |
} | |
pub trait PostDao { | |
fn find_post(&self, id: i32) -> Result<Option<Post>>; | |
} | |
pub trait HavePostDao { | |
type PostDao: PostDao; | |
fn post_dao(&self) -> &Self::PostDao; | |
} | |
struct PostMockDao(); | |
impl PostDao for PostMockDao { | |
fn find_post(&self, id: i32) -> Result<Option<Post>> { | |
Ok(Some(Post { id })) | |
} | |
} | |
trait UserService: HaveUserDao { | |
fn get_user_by_id(&self, id: i32) -> Result<Option<User>> { | |
self.user_dao().find_user(id) | |
} | |
} | |
impl<T:HaveUserDao> UserService for T {} | |
trait HaveUserService { | |
type UserService: UserService; | |
fn user_service(&self) -> &Self::UserService; | |
} | |
trait GroupService: HaveUserDao + HavePostDao { | |
fn show_by_id(&self, id: i32) { | |
println!("{:?}", self.user_dao().find_user(id)); | |
println!("{:?}", self.post_dao().find_post(id)); | |
} | |
} | |
impl<T: HaveUserDao + HavePostDao> GroupService for T {} | |
trait HaveGroupService { | |
type GroupService: GroupService; | |
fn group_service(&self) -> &Self::GroupService; | |
} | |
struct App { | |
user_dao: UserMockDao, | |
post_dao: PostMockDao, | |
} | |
impl HaveUserDao for App { | |
type UserDao = UserMockDao; | |
fn user_dao(&self) -> &Self::UserDao { | |
&self.user_dao | |
} | |
} | |
impl HavePostDao for App { | |
type PostDao = PostMockDao; | |
fn post_dao(&self) -> &Self::PostDao { | |
&self.post_dao | |
} | |
} | |
impl HaveUserService for App { | |
type UserService = Self; | |
fn user_service(&self) -> &Self::UserService { | |
self | |
} | |
} | |
impl HaveGroupService for App { | |
type GroupService = Self; | |
fn group_service(&self) -> &Self::GroupService { | |
self | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment