manytimesthethathingsthatwww.wecan.com'tchange,wechangei

歌词里有that we can baby we can....._百度知道Make Each Day Your Masterpiece
Posted in: , , ,
“Destiny is not a matter of chance. It’s a matter of choice. It is not a thing to be waited for, it is a thing to be achieved.”~William Jennings Bryant
Reading time: 6-8 minutes
It’s early in the morning.
Your alarm goes off.
Beep, beep, beep.
You open your eyes, feeling groggy and disoriented.
Still half-asleep, you try to figure out what’s going on.
Then you remember.
Last night, feeling particularly inspired, you decided you’d get up early and go for a run before heading to work.
Ahhhh shit.
Your bed feels so warm, so comfy, like a little cocoon.
You close your eyes again. You know you have to make a decision.
You can take the easy way out, hit snooze and go back to sleep…
Or take the highest road, put on your running shoes, and head out the door.
The choice is yours and only yours… What will it be?
Every single day, we’re faced with countless little decisions like this one.
In these moments, we have to decide between what’s good for us… and what’s easy, comfortable, safe.
Individually, most of these decisions are fairly inconsequential.
But together, they add up. They compound.
And it’s the sum of all these micro-decisions that determines our destiny.
Consistently take the higher road and you’ll achieve your biggest goals, reach greatness, and maybe even change the world.
Take the easy way out too often and you’ll live a life of mediocrity, constantly disappointing yourself… Until one day, you look back in regret, wondering… “What if?”
Imagine for a second that there was a switch in your brain that would allow you to efficiently smash through your daily to-do list, eat only foods that are good for you, and never skip a workout again.
How would your life be different then?
You, my friend, have the power to develop that switch.
As Roy F. Baumeister, PhD, author of the book
tells us, “willpower is not a personality trait, a skill or a virtue. Instead, it operates like a muscle. And as such, it can be strengthened.”
By implementing the strategies I’m about to share with you. Use them consistently, and you will acquire superhuman willpower, extraordinary self-discipline, and the ability to get anything done on command.
Right here, right now, as you’re reading this, you’re at a crossroads in your life.
You can stick to your old habits and patterns, knowing deep down you’re not living nearly at the level you’re capable of…
Or you can use this article as a springboard towards greatness by implementing the strategies it contains.
Today could be the day you start developing superhuman willpower and discipline.
The choice is yours and only yours… What will it be?
1. Meditate like a Zen Buddhist Monk
Kelly McGonigal Ph.D, who teaches a class on The Science of Willpower at Stanford University, ranks meditation as the #1 way to increase willpower.
She says, “Practicing mindfulness meditation for a few minutes each day can actually boost willpower by building up gray matter in areas of the brain that regulate emotions and govern decision making.”
I’ve personally been meditating every day for the past 2 years, and it’s the single-best habit I’ve developed since I got into personal development and optimal living.
To find out more about how you can get started with meditation, enter your email below to receive a free copy of my eBook The Ultimate Beginner’s Guide to Meditation.
You can also check out , which is the meditation audio system I personally use every morning.
2. Take the Magic Pill of Exercise
The more I research the benefits of exercise, the more I see it as a magic pill.
Not only does it increase our fitness and mental performance, improve our mood and sleep quality, reduce our body fat percentage, anxiety levels and likelihood of becoming sick… It’s also been shown to improve our willpower.
In a 2006 , participants were given free gym memberships and personalized training programs. The study participants who regularly exercised reported:
“Significant decreases in perceived stress, emotional distress, smoking, alcohol and caffeine consumption, and an increase in healthy eating, emotional control, maintenance of household chores, attendance to commitments, monitoring of spending and an improvement in study habits”.
Even 5 minutes a day will make a difference but I recommend shooting for at least 30 minutes, 3 times a week.
Find something you love (ie, if you hate running on a treadmill, DON’T do that), have fun doing it, and work on making it a regular part of your life.
If you don’t like exercising, it’s not because you’re “not made for it”. It’s because you haven’t found the type of exercise that’s right for you.
Keep looking. It’s worth it.
#3 Harness the Power of Accountability
Admittedly, accountability isn’t the sexiest word in the English language. But the concept it represents is extremely powerful.
The idea behind it is that when we’re left to our own devices, it’s easy to come up with excuses not to do something.
“I’m tired, I don’t feel like it, it’s too much work, it’s too hard.”
Blah blah blah.
Let’s be real. 99% of it is just excuses our “small self” makes to stay comfortable and avoid stepping into greatness.
The solution is simple: build structures in your life that will hold you to a higher standard and that will prevent you from coming up with excuses.
There are several ways to do this. Here are a few to consider:
Get an , a workout partner, work side-by-side with a coworker (or friend),, join (or create) a mastermind group, or use the website .
Whatever specific system you use, the most important thing is that it takes away your ability to procrastinate and make excuses, and that it makes you stick to your plan and highest values.
#4 Set SMART Goals
When someone emails me asking how they could have more discipline and willpower, my first question to them is always, “do you have clear goals for yourself?”
90+% of the time, the answer is no. Oops.
Why is it so important to have defined goals?
Because they give you a clear direction in life and help you connect your daily actions to a greater purpose.
When I was at , I asked Ryan Ellis, a 28-year old entrepreneur who sold his first company for $169 million what his number one advice for young ambitious people was.
He said, “clearly define your goals, print them out, and put them up on your bedroom wall.”
Simple enough.
When you create your goals, make sure they are SMART:
Measurable
Attainable
For instance, don’t set a goal of “I want to lose weight” or “I want to make more money”.
Instead, it should look more like “I want to lose 10 lbs of body fat by March 1st” or “I want to increase my monthly income by $5000 by June 10”.
Once you do that, taking action and staying disciplined every day will be infinitely easier. You’ll be “pulled” towards the achievement of your goals, and you’ll feel a great sense of purpose and fulfilment.
#5 Unleash Your Inner Conquistador and Burn the Ships
In 1519, a Spanish conquistador named Hernan Cortez made a bold-as-hell, history-changing decision we can all learn from.
He sailed from Spain to South America with a fleet of 11 ships, and upon arriving to the new land, realized that his troops would have to fight the natives in order to claim the land.
His men were tired, malnourished and out of shape from the long journey across the Atlantic. Many of them didn’t want to fight.
Cortez knew they had to do this. He ordered everyone to go on the beach, and once he was the only one left on the ships, he proceeded to burn them all (!).
Now his men had no option to retreat. So they gathered up all their strength and courage, fought, and claimed the land that is now known as Mexico.
Pretty damn bold, right?
Now, how does this apply to you?
If you have a big project to complete, and you’re struggling to discipline yourself, burn your ships.
Engineer a situation that will prevent you from retreating and that will force you to get into action mode.
For instance, before I created The Superhuman Blueprint, I sent out an email on September 1st telling more than 2000 people that the course was going to start on October 8th.
At that point, I had yet to build any of the content or marketing material.
But now I had burned the ships. I had no choice but to get it done. And I did.
Moving forward, I’ve decided to use this strategy for all my major projects, and I highly suggest you do the same. It’s astonishing what we can do when we take away our escape route.
#6 Remove Temptations and Distractions
All humans are subject to temptation—it’s just in our nature.
And in today’s world we’re surrounded by more temptations than ever.
Google gives us access to all the information in the world within a few seconds. YouTube is filled with funny, entertaining, and interesting videos. Our Facebook newsfeed gets updated every few seconds. Our smart phones are full of apps and other cool things.
Knowing this, it’s imperative to figure out a system to bulletproof ourselves against all these distractions.
First, identify what are your common distractions are.
Second, build a structure to mitigate them.
Here are a few of the particular strategies I use:
-Using , a web-app that allows me to “block out” my internet for a set period of time.
-Using , a Chrome web-app that allows me to block out chosen websites for certain parts of the day (Thanks to Max Nachamkin from
for the tip)
-Putting my phone on Airplane mode while working.
-Keeping only healthy foods in my fridge/cupboards.
Once the temptations are removed, you can direct all your willpower to doing great things instead of fighting the urge to procrastinate yet again.
#7 Eat the Big Ugly Frog First
Another discovery Roy F. Baumeister PhD made during his research is that we only have a finite amount of willpower each day.
Our willpower is at its highest at the beginning of the day, and progressively decreases as we go about our business.
Knowing this, we want to engineer our day so as to do our most challenging tasks in the morning, when we are fresh and rested.
In his book The 4-Hour Workweek, Tim Ferriss talks at lengths about Pareto’s Law (also known as the 80/20 rule) which states that 20% of our input creates 80% of our output.
For more about Pareto’s Law, .
Every morning, get clear on what your 20% is. If you’re not sure what that 20% is, it’s generally the most uncomfortable/challenging task you have to do all day. Once you figure out what it is, roll up your sleeves and get it done.
#8 Eliminate Unnecessary Decisions
When asked about , President Barrack Obama said, “I don’t want to make decisions about what I’m eating or wearing because I have too many other decisions to make.”
As Baumeiseter found, every single decision we make during the day dips into our willpower reserves. Therefore, we need to cut down the number of decision we make to a minimum, and focus on the most important ones.
I personally have the same breakfast () and lunch (mixed green salad with a chicken breast and a half-cup of quinoa or beans) every day. I never spend more than 15 seconds deciding what I’m going to wear today. And I’m learning to empower my team to take more decisions without seeking my approval.
As you go through the day, try to pay attention to where you are getting hung up in your decision process.
Try to eliminate or minimize all the unimportant, and preserve your brainpower for what truly matters.
#9 Create Powerful Habits, Rituals and Routines
Building on the last point, creating rituals is a great way to remove needless decision-making from your day.
Once something has been turned into a habit, you don’t even have to think about it. You do it without using any of your willpower.
Every morning, I start my day with the same 60-minute power routine to get me in an optimal physical, emotional and intellectual state.
Each step of the ritual is carefully choreographed for optimal results, yet it requires no willpower on my part because it’s engrained in my ritual.
To learn how to craft your optimal morning ritual, enter your email below to receive a free copy of my eBook How to Supercharge Your Morning.
Look for all the ways you can “routinize” your life, and you’ll gain the double benefit of having better habits while conserving more of your willpower.
#10 Hack Your Mind with the 5-Minute Rule
Our mind can be our greatest ally… and our greatest foe.
The trick is to be aware of its inner workings, both its strengths and its weaknesses, and optimize around them.
One of our mind’s greatest flaws is that it often struggles to get things started. But once we’re in flow, it’s easy to keep going.
If you’re struggling to get started on some work you have to do, or to start your daily meditation/workout, make the following deal with yourself: you’ll do it for just 5 minutes.
Answer one email. Run 1 time around your block. Meditate for 5 minutes.
From personal experience and discussing it with others, I’ve found that 80 to 90% of the time, once we’re in motion, we end up continuing well past the 5-minute mark we had decided on.
This is truly a Jedi Mind Trick we can use on ourselves.
#11 Go for 100% Commitment
Jack Canfield, author of the book Chicken Soup for the Soul famously said “99% is a bitch, 100% is a breeze.”
If you really want to do something, commit to it 100%.
If you’re just sorta-committed, there’ll always be a little voice in your head saying “aahh, maybe today I’ll take the day off“. You’ll waste a lot of willpower fighting off that little voice.
But the moment have you that 100% commitment, the game becomes easy. You don’t have to think about it… you just do it!
Conclusion
One of my teachers once told me, “our human spirit is the greatest gift we’ve been given.”
That human spirit is what built magnificent cathedrals, explored far-away lands, and created world-changing technologies.
That force is inside of you, it’ it’s inside all of us.
And it’s your duty to put it to good use. For yourself, for those around you, and for the next generations.
You, my friend, have been bestowed with some unique gifts, talents and passions. You can do things that no one else in this world can do. Seriously.
And we need you to rise up and shine. To be a beacon of light, love and inspiration for others.
So please take the teachings I’ve shared with you today seriously.
They will change your life. And you, in turn, can go out there and change the world.
Choose Greatness,
Please share this post because that’s how more people can develop extraordinary willpower.
My deepest belief is that there is greatness inside all of us.
And to access it, we must align ourselves with a greater purpose, commit to excellence, and seek to improve every day.
I'm a , a triathlete and a lover of wisdom.
On this website, I help unleash your full potential, create a life you love, and achieve the dreams that light your heart on fire.
Click below to follow me on Facebook where I post often.
Hit “Like” To Stay Updated
Product I love & recommend
Hottest Posts Right Now!7 Things I Learned From The Finale Of How I Met Your Mother | Thought Catalog
7 Things I Learned From The Finale Of How I Met Your&Mother
Report This Article
What is the issue?
Infringes my copyright
Visually pornographic content
Hateful or weaponized writing
Spam or misleading text
1. Time sucks and people change.
If you think about it for all the avid watchers of HIMYM we have watched this show for nine straight years. So we have watched the time pass in all these characters live and when that happens, just like in the real world, they get older just like we have and things change. P we lose loved ones, we get married, we have kids, we move away, and we meet new people.
And as much as we want to hang on to time, just like Lily did, we can’t because the more we hold on to things like that the more bitter we become and the more we stop focusing on all the good things coming in the future.
2. One moment can change things in your life and yourself forever.
Barney never would have changed if he didn’t get someone pregnant and he would have spent years as a bachelor and ultimately ending up alone. That baby girl changed his life and showed us all that even though he wasn’t ultimately capable of loving Robin or anyone in a romantic way it still showed that Barney was a loving human being who had a heart and that in the one moment of meeting his daughter he changed right before our eyes.
3. Life is for the living.
We often forget and succumb to being selfish when people die in our lives. We make ourselves think that we should all stop living when someone we love dies and that’s not fair.
So no the show shouldn’t be called “How I Met Your Mother, but I Really Wanted To Bang Aunt Robin” because Ted didn’t go “bang” Robin right after his soul mate died he waited six year, he raised his children, children who obviously loved him enough to listen to that long of a story, he wasn’t selfish he was selfless. Was Ted supposed to stay alone? Ask yourselves out of all the people on this show did you really want ted to be alone?
4. Right person wrong time.
I know everyone is pissed off that the writers supposedly spent eight seasons saying that Ted and Robin weren’t right for each other but in reality the only reason that Ted and Robin didn’t work was because when they dated they wanted very very very different things in life. Ted met his soul mate, they got married (eventually), they shared all their corny hobbies, and most importantly they created a beautiful family together. If Tracy had not died Ted would have always been in deep love with her, but unfortunately life doesn’t always work out the way we want it to.
Who is to say they weren’t right for each other? Robin never wanted to have kids and that wouldn’t have been fair for Ted to force her to do that on top of the fact that she couldn’t provide the love a mom should because that was just something she wasn’t capable of, ultimately they could have ended up in a divorce just as well. It was finally the right time for both of them it made perfect sense for the two of them to be together…and the blue French horn. This wasn’t nine wasted seasons just because it didn’t make sense to you for Robin and Ted to be together. Because in the second to last episode Ted says to Robin, “Love isn’t supposed to make sense.”
5. Everything happens for a reason.
If you don’t believe in that get over it because it’s true. Great things happen to you in life to get you where you are, but shitty things are going to happen to you and it will help you get to the same place. Every character on this show went through hardships in their lives that brought them to that season finale right where they belonged. Were their lives perfect? No. But in the end they were all happy and that is what mattered most.
6. “The road of life twists and turns and no two directions are ever the same.
Yet our lessons come from the journey, not the destination.” (Don Williams, Jr) You didn’t waste nine years of your life on this show because you got exactly what the title said, how Ted met the mother. This was about Ted’s journey with his friends who helped him get through what seemed like the worst times in his life and celebrated with him during the best.
Life isn’t ever about the destination its about the memories, hardships, and triumphs that come before. This show was way more than just about the mother don’t forget that.
7. In life we don’t get answers to everything we ask.
Think about it, where is the goddamn pineapple.
Crushed after the season finale? Get more HIMYM with our new Thought Catalog Book .
Follow Niki on
More from Thought Catalog
Niki’s Popular Articles
Our favorites, every Friday.
Hosting by
Powered byThe public getAttack() function lets the combat code get the string that
should be displayed when the monster attacks the hero. Each derived breed class
will override this to provide a different message.
The constructor is protected and takes the starting health for the monster.
We’ll have derived classes for each breed that provide their own public
constructors that call this one, passing in the starting health that is
appropriate for that breed.
Now let’s see a couple of breed subclasses:
class Dragon : public Monster
Dragon() : Monster(230) {}
virtual const char* getAttack()
return &The dragon breathes fire!&;
class Troll : public Monster
Troll() : Monster(48) {}
virtual const char* getAttack()
return &The troll clubs you!&;
Exclamation points make everything more exciting!
Each class derived from Monster passes in the starting health and overrides
getAttack() to return the attack string for that breed. Everything works as
expected, and before long, we’ve got our hero running around slaying a variety of
beasties. We keep slinging code, and before we know it, we’ve got dozens of
monster subclasses, from acidic slimes to zombie goats.
Then, strangely, things start to bog down. Our designers ultimately want to have
hundreds of breeds, and we find ourselves spending all of our time writing
these little seven-line subclasses and recompiling. It gets worse & the designers
want to start tuning the breeds we’ve already coded. Our formerly productive
workday degenerates to:
Get email from designer asking to change health of troll from
Check out and change Troll.h.
Recompile game.
Check in change.
Reply to email.
We spend the day frustrated because we’ve turned into data monkeys. Our
designers are frustrated because it takes them forever to get a simple
number tuned. What we need is the ability to change breed stats without having
to recompile the whole game every time. Even better, we’d like designers to be
able to create and tune breeds without any programmer intervention at all.
At a very high level, the problem we’re trying to solve is pretty simple. We
have a bunch of different monsters in the game, and we want to share certain
attributes between them. A horde of monsters are beating on the hero, and we
want some of them to use the same text for their attack. We define that by
saying that all of those monsters are the same “breed”, and that the breed
determines the attack string.
We decided to implement this concept using inheritance since it lines up with
our intuition of classes. A dragon is a monster, and each dragon in the game is
an instance of this dragon “class”. Defining each breed as a subclass of an
abstract base Monster class, and having each monster in the game be an
instance of that derived breed class mirrors that. We end up with a class
hierarchy like this:
means “inherits
from”.
Each instance of a monster in the game will be of one of the derived monster
types. The more breeds we have, the bigger the class hierarchy. That’s the
problem of course: adding new breeds means adding new code, and each breed has
to be compiled in as its own type.
This works, but it isn’t the only option. We could also architect our code so
that each monster has a breed. Instead of subclassing Monster for each
breed, we have a single Monster class and a single Breed class:
means “is
referenced by”.
That’s it. Two classes. Notice that there’s no inheritance at all. With this
system, each monster in the game is simply an instance of class Monster. The
Breed class contains the information that’s shared between all monsters of the
same breed: starting health and the attack string.
To associate monsters with breeds, we give each Monster instance a reference
to a Breed object containing the information for that breed. To get the attack
string, a monster just calls a method on its breed. The Breed class
essentially defines a monster’s “type”. Each breed instance is an object that
represents a different conceptual type, hence the name of the pattern: Type
What’s especially powerful about this pattern is that now we can define new
types of things without complicating the codebase at all. We’ve essentially
lifted a portion of the type system out of the hard-coded class hierarchy into
data we can define at runtime.
We can create hundreds of different breeds by instantiating more instances
of Breed with different values. If we create breeds by initializing them from
data read from some configuration file, we have the ability to define new types
of monsters completely in data. So easy, a designer could do it!
Define a type object class and a typed object class. Each type object
instance represents a different logical type. Each typed object stores a
reference to the type object that describes its type.
Instance-specific data is stored in the typed object instance, and data or
behavior that should be shared across all instances of the same conceptual type
is stored in the type object. Objects referencing the same type object will
function as if they were the same type. This lets us share data and behavior
across a set of similar objects, much like subclassing lets us do, but without
having a fixed set of hard-coded subclasses.
This pattern is useful anytime you need to define a variety of different “kinds”
of things, but baking the kinds into your language’s type system is too rigid.
In particular, it’s useful when either of these is true:
You don’t know what types you will need up front. (For example, what if our
game needed to support downloading content that contained new breeds of
monsters?)
You want to be able to modify or add new types without having to recompile
or change code.
This pattern is about moving the definition of a “type” from the imperative but
rigid language of code into the more flexible but less behavioral world of
objects in memory. The flexibility is good, but you lose some things by hoisting
your types into data.
One advantage of using something like C++’s type
system is that the compiler handles all of the bookkeeping for the classes
automatically. The data that defines each class is automatically compiled into
the static memory segment of the executable and just works.
With the Type Object pattern, we are now responsible for managing not only our
monsters in memory, but also their types & we have to make sure all of the
breed objects are instantiated and kept in memory as long as our monsters need
them. Whenever we create a new monster, it’s up to us to ensure that it’s
correctly initialized with a reference to a valid breed.
We’ve freed ourselves from some of the limitations of the compiler, but the cost
is that we have to re-implement some of what it used to be doing for us.
Under the hood, C++ virtual methods are implemented using something called a
“virtual function table”, or just “vtable”. A vtable is a simple struct
containing a set of function pointers, one for each virtual method in a class.
There is one vtable in memory for each class. Each instance of a class has a
pointer to the vtable for its class.
When you call a virtual function, the code first looks up the vtable for the
object, then it calls the function stored in the appropriate function pointer in
the table.
Sound familiar? The vtable is our breed object, and the pointer to the vtable is
the reference the monster holds to its breed. C++ classes are the Type Object
pattern applied to C, handled automatically by the compiler.
With subclassing, you can override a method and do whatever you want to —
calculate values procedurally, call other code, etc. The sky is the limit. We
could define a monster subclass whose attack string changed based on the phase
of the moon if we wanted to. (Handy for werewolves, I suppose.)
When we use the Type Object pattern instead, we replace an overridden method
with a member variable. Instead of having monster subclasses that override a
method to calculate an attack string using different code, we have a breed
object that stores an attack string in a different variable.
This makes it very easy to use type objects to define type-specific data, but
hard to define type-specific behavior. If, for example, different breeds of
monster needed to use different AI algorithms, using this pattern becomes more
challenging.
There are a couple of ways we can get around this limitation. A simple solution
is to have a fixed set of pre-defined behaviors and then use data in the type
object to simply select one of them. For example, let’s say our monster AI
will always be either “stand still”, “chase hero”, or “whimper and cower in
fear” (hey, they can’t all be mighty dragons). We can define functions to implement each of those behaviors. Then, we can
associate an AI algorithm with a breed by having it store a pointer to
the appropriate function.
Sound familiar again? Now we’re back to really implementing vtables in our
type objects.
Another more powerful solution is to actually support defining behavior
completely in data. The
and Bytecode patterns both let us build
objects that represent behavior. If we read in a data file and use that to
create a data structure for one of these patterns, we’ve moved the behavior’s
definition completely out of code and into content.
Over time, games are getting more data-driven. Hardware gets more powerful, and
we find ourselves limited more by how much content we can author than how hard
we can push the hardware. With a 64K cartridge, the challenge was cramming the
gameplay into it. With a double-sided DVD, the challenge is filling it with
Scripting languages and other higher-level ways of defining game behavior can
give us a much needed productivity boost, at the expense of less optimal runtime
performance. Since hardware keeps getting better but our brainpower doesn’t,
that trade-off starts to make more and more sense.
For our first pass at an implementation, let’s start simple and build the basic
system described in the motivation section. We’ll start with the Breed
class Breed
Breed(int health, const char* attack)
: health_(health),
attack_(attack)
int getHealth() { return health_; }
const char* getAttack() { return attack_; }
int health_; // Starting health.
const char* attack_;
Very simple. It’s basically just a container for two data fields: the starting
health and the attack string. Let’s see how monsters use it:
class Monster
Monster(Breed& breed)
: health_(breed.getHealth()),
breed_(breed)
const char* getAttack()
return breed_.getAttack();
health_; // Current health.
Breed& breed_;
When we construct a monster, we give it a reference to a breed object. This
defines the monster’s breed instead of the subclasses we were previously using.
In the constructor, Monster uses the breed to determine its starting health.
To get the attack string, the monster simply forwards the call to its breed.
This very simple chunk of code is the core idea of the pattern. Everything from
here on out is bonus.
With what we have now, we construct a monster directly and are responsible for
passing in its breed. This is a bit backwards from how regular objects are
instantiated in most OOP languages & we don’t usually allocate a blank chunk of
memory and then give it its class. Instead, we call a constructor function on
the class itself, and it’s responsible for giving us a new instance.
We can apply this same pattern to our type objects:
class Breed
Monster* newMonster() { return new Monster(*this); }
// Previous Breed code...
“Pattern” is the right word here. What we’re talking about is one of the classic
patterns from Design Patterns: .
In some languages, this pattern is applied for constructing all objects. In
Ruby, Smalltalk, Objective-C, and other languages where classes are objects, you
construct new instances by calling a method on the class object itself.
And the class that uses them:
class Monster
friend class Breed;
const char* getAttack() { return breed_.getAttack(); }
Monster(Breed& breed)
: health_(breed.getHealth()),
breed_(breed)
int health_; // Current health.
Breed& breed_;
The key difference is the newMonster() function in
Breed. That’s our “constructor” factory method. With our original
implementation, creating a monster looked like:
There’s another minor difference here. Because the sample code is in C++, we can
use a handy little feature: friend classes.
We’ve made Monster&s constructor private, which prevents anyone from
calling it directly. Friend classes sidestep that restriction so Breed can
still access it. This means the only way to create monsters is by going
through newMonster().
Monster* monster = new Monster(someBreed);
After our changes, it’s like this:
Monster* monster = someBreed.newMonster();
So, why do this? There are two steps to creating an object: allocation and
initialization. Monster&s constructor lets us do all of the
initialization we need. In our example, that’s only storing the breed, but a
full game would be loading graphics, initializing the monster’s AI, and doing
other set-up work.
However, that all happens after allocation. We’ve already got a chunk of
memory to put our monster into before its constructor is called. In games, we
often want to control that aspect of object creation too: we’ll typically use
things like custom allocators or the
pattern to control where in memory our
objects end up.
Defining a “constructor” function in Breed gives us a place to put that logic.
Instead of simply calling new, the newMonster() function can pull the memory
from a pool or custom heap before passing control off to Monster for
initialization. By putting this logic inside Breed, in the only function
that has the ability to create monsters, we ensure that all monsters go through
the memory management scheme we want.
What we have so far is a perfectly serviceable type object system, but it’s
pretty basic. Our game will eventually have hundreds of different breeds, each
with dozens of attributes. If a designer wants to tune all of the thirty
different breeds of troll to make them a little stronger, she’s got a lot of
tedious data entry ahead of her.
What would help is the ability to share attributes across multiple breeds in
the same way that breeds let us share attributes across multiple monsters.
Just like we did with our original OOP solution, we can solve this using
inheritance. Only, this time, instead of using our language’s inheritance
mechanism, we’ll implement it ourselves within our type objects.
To keep things simple, we’ll only support single inheritance. In the same way
that a class can have a parent base class, we’ll allow a breed to have a parent
class Breed
Breed(Breed* parent, int health, const char* attack)
: parent_(parent),
health_(health),
attack_(attack)
getHealth();
const char* getAttack();
health_; // Starting health.
const char* attack_;
When we construct a breed, we give it a parent that it inherits from. We can
pass in NULL for a base breed that has no ancestors.
To make this useful, a child breed needs to control which attributes are
inherited from its parent and which attributes it overrides and specifies itself. For our
example system, we’ll say that a breed overrides the monster’s health by having
a non-zero value and overrides the attack by having a non-NULL string.
Otherwise, the attribute will be inherited from its parent.
There are two ways we can implement this. One is to handle the delegation
dynamically every time the attribute is requested, like this:
int Breed::getHealth()
// Override.
if (health_ != 0 || parent_ == NULL) return health_;
// Inherit.
return parent_-&getHealth();
const char* Breed::getAttack()
// Override.
if (attack_ != NULL || parent_ == NULL) return attack_;
// Inherit.
return parent_-&getAttack();
This has the advantage of doing the right thing if a breed is modified at
runtime to no longer override, or no longer inherit some attribute. On the other
hand, it takes a bit more memory (it has to retain a pointer to its parent), and
it’s slower. It has to walk the inheritance chain each time you look up an
attribute.
If we can rely on a breed’s attributes not changing, a faster solution is to
apply the inheritance at construction time. This is called “copy-down”
delegation because we copy inherited attributes down into the derived type
when it’s created. It looks like this:
Breed(Breed* parent, int health, const char* attack)
: health_(health),
attack_(attack)
// Inherit non-overridden attributes.
if (parent != NULL)
if (health == 0) health_ = parent-&getHealth();
if (attack == NULL) attack_ = parent-&getAttack();
Note that we no longer need a field for the parent breed. Once the constructor
is done, we can forget the parent since we’ve already copied all of its
attributes in. To access a breed’s attribute, now we just return the field:
getHealth() { return health_; }
const char* getAttack() { return attack_; }
Nice and fast!
Let’s say our game engine is set up to create the breeds by loading a JSON file
that defines them. It could look like:
&Troll&: {
&health&: 25,
&attack&: &The troll hits you!&
&Troll Archer&: {
&parent&: &Troll&,
&health&: 0,
&attack&: &The troll archer fires an arrow!&
&Troll Wizard&: {
&parent&: &Troll&,
&health&: 0,
&attack&: &The troll wizard casts a spell on you!&
We’d have a chunk of code that reads each breed entry and instantiates a new
breed instance with its data. As you can see from the "parent": "Troll"
fields, the Troll Archer and Troll Wizard breeds inherit from the base
Troll breed.
Since both of them have zero for their health, they’ll inherit it from the base
Troll breed instead. This means now our designer can tune the health in
Troll and all three breeds will be updated. As the number of breeds and the
number of different attributes each breed has increase, this can be a big
time-saver. Now, with a pretty small chunk of code, we have an open-ended system
that puts control in our designers’ hands and makes the best use of their time.
Meanwhile, we can get back to coding other features.
The Type Object pattern lets us build a type system as if we were designing our
own programming language. The design space is wide open, and we can do all sorts
of interesting stuff.
In practice, a few things curtail our fancy. Time and maintainability will
discourage us from anything particularly complicated. More importantly, whatever
type object system we design, our users (often non-programmers) will need to be
able to easily understand it. The simpler we can make it, the more usable it
will be. So what we’ll cover here is the well-trodden design space, and we’ll
leave the far reaches for the academics and explorers.
In our sample implementation, Monster has a reference to a breed, but it
doesn’t publicly expose it. Outside code can’t get directly at the monster’s
breed. From the codebase’s perspective, monsters are essentially typeless, and
the fact that they have breeds is an implementation detail.
We can easily change this and allow Monster to return its Breed:
class Monster
Breed& getBreed() { return breed_; }
// Existing code...
As in other examples in this book, we’re following a convention where we return
objects by reference instead of pointer to indicate to users that NULL will
never be returned.
Doing this changes the design of Monster. The fact that all monsters have
breeds is now a publicly visible part of its API. There are benefits with either
If the type object is encapsulated:
The complexity of the Type Object pattern is hidden from the rest of
the codebase. It becomes an implementation detail that only the typed
object has to worry about.
The typed object can selectively override behavior from the type
object. Let’s say we wanted to change the monster’s attack string when
it’s near death. Since the attack string is always accessed through
Monster, we have a convenient place to put that code:
const char* Monster::getAttack()
if (health_ & LOW_HEALTH)
return &The monster flails weakly.&;
return breed_.getAttack();
If outside code was calling getAttack() directly on the breed, we
wouldn’t have the opportunity to insert that logic.
We have to write forwarding methods for everything the type object
exposes. This is the tedious part of this design. If our type object
class has a large number of methods, the object class will have to have
its own methods for each of the ones that we want to be publicly
If the type object is exposed:
Outside code can interact with type objects without having an instance
of the typed class. If the type object is encapsulated, there’s no way
to use it without also having a typed object that wraps it. This
prevents us, for example, from using our constructor pattern where new
monsters are created by calling a method on the breed. If users can’t
get to breeds directly, they wouldn’t be able to call it.
The type object is now part of the object’s public API. In general,
narrow interfaces are easier to maintain than wide ones & the less you
expose to the rest of the codebase, the less complexity and maintenance
you have to deal with. By exposing the type object, we widen the
object’s API to include everything the type object provides.
With this pattern, each “object” is now a pair of objects: the main object and
the type object it uses. So how do we create and bind the two together?
Construct the object and pass in its type object:
Outside code can control allocation. Since the calling code is
constructing both objects itself, it can control where in memory that
occurs. If we want our objects to be usable in a variety of different
memory scenarios (different allocators, on the stack, etc.) this gives
us the flexibility to do that.
Call a “constructor” function on the type object:
The type object controls memory allocation. This is the other side of
the coin. If we don’t want users to choose where in memory our objects
are created, requiring them to go through a factory method on the type
object gives us control over that. This can be useful if we want to
ensure all of our objects come from a certain
or other memory allocator.
So far, we’ve presumed that once an object is created and bound to its type
object that that binding will never change. The type an object is created with
is the type it dies with. This isn’t strictly necessary. We could allow an
object to change its type over time.
Let’s look back at our example. When a monster dies, the designers tell us
sometimes they want its corpse to become a reanimated zombie. We could implement
this by spawning a new monster with a zombie breed when a monster dies, but
another option is to simply get the existing monster and change its breed to a
zombie one.
If the type doesn’t change:
It’s simpler both to code and to understand. At a conceptual level,
“type” is something most people probably will not expect to change. This
codifies that assumption.
It’s easier to debug. If we’re trying to track down a bug where a
monster gets into some weird state, it simplifies our job if we can take
for granted that the breed we’re looking at now is the breed the
monster has always had.
If the type can change:
There’s less object creation. In our example, if the type can’t
change, we’ll be forced to burn CPU cycles creating a new zombie
monster, copying over any attributes from the original monster that need
to be preserved, and then deleting it. If we can change the type,
all that work gets replaced by a simple assignment.
We need to be careful that assumptions are met. There’s a fairly tight
coupling between an object and its type. For example, a breed might
assume that a monster’s current health is never above the starting
health that comes from the breed.
If we allow the breed to change, we need to make sure that the new
type’s requirements are met by the existing object. When we change the
type, we will probably need to execute some validation code to make sure
the object is now in a state that makes sense for the new type.
No inheritance:
It’s simple. Simplest is often best. If you don’t have a ton of data
that needs sharing between your type objects, why make things hard on
It can lead to duplicated effort. I’ve yet to see an authoring system
where designers didn’t want some kind of inheritance. When you’ve got
fifty different kinds of elves, having to tune their health by changing
the same number in fifty different places sucks.
Single inheritance:
It’s still relatively simple. It’s easy to implement, but, more
importantly, it’s also pretty easy to understand. If non-technical users
are going to be working with the system, the fewer moving parts, the
better. There’s a reason a lot of programming languages only support
single inheritance. It seems to be a sweet spot between power and
simplicity.
Looking up attributes is slower. To get a given piece of data from a
type object, we might need to walk up the inheritance chain to find
the type that ultimately decides the value. If we’re in
performance-critical code, we may not want to spend time on this.
Multiple inheritance:
Almost all data duplication can be avoided. With a good multiple
inheritance system, users can build a hierarchy for their type objects
that has almost no redundancy. When it comes time to tune numbers, we
can avoid a lot of copy and paste.
It’s complex. Unfortunately, the benefits for this seem to be more
theoretical than practical. Multiple inheritance is hard to understand
and reason about.
If our Zombie Dragon type inherits both from Zombie and Dragon, which
attributes come from Zombie and which come from Dragon? In order to use
the system, users will need to understand how the inheritance graph is
traversed and have the foresight to design an intelligent hierarchy.
Most C++ coding standards I see today tend to ban multiple inheritance,
and Java and C# lack it completely. That’s an acknowledgement of a sad
fact: it’s so hard to get it right that it’s often best to not use it at
all. While it’s worth thinking about, it’s rare that you’ll want to use
multiple inheritance for the type objects in your games. As always,
simpler is better.
The high-level problem this pattern addresses is sharing data and behavior
between several objects. Another pattern that addresses the same problem in
a different way is .
Type Object is a close cousin to . Both let you share data across
instances. With Flyweight, the intent is on saving memory, and the shared
data may not represent any conceptual “type” of object. With the Type Object
pattern, the focus is on organization and flexibility.
There’s a lot of similarity between this pattern and the State pattern. Both patterns let
an object delegate part of what defines itself to another object. With a
type object, we’re usually delegating what the object is: invariant data
that broadly describes the object. With State, we delegate what an object
is right now: temporal data that describes an object’s current
configuration.
When we discussed having an object change its type, you can look at that as
having our Type Object serve double duty as a State too.
Robert Nystrom}

我要回帖

更多关于 wecan 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信